上传文件代码
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@RestController
@RequestMapping(path = "/file")
public class FileController {
/*上传文件的路径*/
static final String PATH = "D:\\picture";
@RequestMapping(path = "/fileUpload")
// public String fileUpload(MultipartFile[] file) {
public String fileUpload(MultipartFile file) {
String newFileName = "";
/*生成UUID*/
String uuid = UUID.randomUUID().toString();
/*获取上传文件的全名*/
String fileName = file.getOriginalFilename();
/*截取文件后缀名*/
String suffix = fileName.substring(fileName.lastIndexOf("."));
/*根据path路径创建file对象*/
File realPathFolder = new File(PATH);
/*判断此路径下的目录是否存在,不存在就创建*/
if (!realPathFolder.exists()) {
realPathFolder.mkdirs();
}
/*生成新的文件名称*/
newFileName = uuid + suffix;
/*根据路径和新的文件名创建file对象*/
File newFile = new File(realPathFolder, newFileName);
/*上传图片到指定路径*/
try {
file.transferTo(newFile);
} catch (IOException e) {
System.out.println("上传文件失败!" + e);
}
/*返回访问路径*/
return "localhost:8080/files/" + newFileName;
}
}
设置文件大小限制
spring:
servlet:
multipart:
max-request-size: 100MB
max-file-size: 10MB
# maxFileSize 是单个文件大小
# maxRequestSize是设置总上传的数据大小
配置静态资源访问
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
/*访问时的虚拟路径*/
.addResourceHandler("/files/**")
/*资源真实路径*/
.addResourceLocations("file:D:\\picture\\");
}
}
测试