Sringboot多文件上传
使用form-data格式进行上传,自定义文件路径,文件名
代码
@PostMapping("/textImages")
public Boolean textImages(HttpServletRequest request)throws IOException{
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
String id = request.getParameter("id");
System.out.println(id);
for (MultipartFile file : files) {
if (!file.isEmpty()) {
System.out.println("成功获取照片");
String fileName = file.getOriginalFilename();
String path = null;
String type = null;
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
if (type != null) {
if ("PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
// 项目在容器中实际发布运行的根路径
File realPath = new File(ResourceUtils.getURL("classpath:").getPath());
// 自定义的文件名称
String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
// 设置存放图片文件的路径
//path = realPath.getAbsolutePath() + "uploads/";
System.out.println(realPath.getAbsolutePath());
File filePath = new File(realPath.getAbsolutePath(), "uploads/");
if (!filePath.exists() && !filePath.isDirectory()) {
System.out.println("//不存在");
filePath.mkdir();
} else {
System.out.println("//目录存在");
}
//path += trueFileName;
file.transferTo(new File(filePath, trueFileName));
}
}
}
}
return false;
}
测试
使用postman进行测试,注意这里的Headers为空
设置上传文件大小
方法一:通过修改application.yml文件
spring:
http:
multipart:
max-file-size: 10Mb
max-request-size: 30Mb
但是这种方法似乎不起作用
方法二:
在启用类中注入
@SpringBootApplication
public class SfApplication {
public static void main(String[] args) {
SpringApplication.run(SfApplication.class, args);
}
//设置上传文件大小
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory config = new MultipartConfigFactory();
config.setMaxFileSize("10MB");
config.setMaxRequestSize("100MB");
return config.createMultipartConfig();
}
}