<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
/** * 防止文件大于10M时Tomcat链接重置 * * @return */ @Bean public TomcatServletWebServerFactory tomcatEmbedded() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> { if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) { ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1); } }); return tomcat; }
# 禁用 thymeleaf 缓存 spring.thymeleaf.cache=false # 是否支持批量上传 (默认值 true) spring.servlet.multipart.enabled=true # 上传文件的临时目录 (通常状况下不用特地修改) spring.servlet.multipart.location= # 上传文件最大为 1M (默认值 1M 根据自身业务自行控制便可) spring.servlet.multipart.max-file-size=10MB # 上传请求最大为 10M(默认值10M 根据自身业务自行控制便可) spring.servlet.multipart.max-request-size=10MB # 文件大小阈值,当大于这个阈值时将写入到磁盘,不然存在内存中,(默认值0 通常状况下不用特地修改) spring.servlet.multipart.file-size-threshold=0 # 判断是否要延迟解析文件(至关于懒加载,通常状况下不用特地修改) spring.servlet.multipart.resolve-lazily=false file.upload.path: /file/upload
@PostMapping("/upload") public Map<String, String> upload(@RequestParam MultipartFile file) throws IOException { //建立本地文件 File localFile = new File(path, file.getOriginalFilename()); //把传上来的文件写到本地文件 file.transferTo(localFile); //返回localFile文件路径 Map<String, String> path = new HashMap<>(); path.put("path", localFile.getAbsolutePath()); return path; }
这时候系统将会出现FileNotFoundException
,日志相似下面这样:java
java.io.FileNotFoundException:C:\Users\cheng\AppData\Local\Temp\tomcat.7543349588424487992.9000\work\Tomcat\localhost\ROOT\file\upload\tmp\file\upload\1558332190813.jpg (系统找不到指定的路径。)
这是什么缘由呢?能够进入transferTo
方法git
@Override public void transferTo(File dest) throws IOException, IllegalStateException { this.part.write(dest.getPath()); if (dest.isAbsolute() && !dest.exists()) { // Servlet 3.0 Part.write is not guaranteed to support absolute file paths: // may translate the given path to a relative location within a temp dir // (e.g. on Jetty whereas Tomcat and Undertow detect absolute paths). // At least we offloaded the file from memory storage; it'll get deleted // from the temp dir eventually in any case. And for our user's purposes, // we can manually copy it to the requested location as a fallback. FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath())); } }
然后咱们再进入write
方法github
@Override public void write(String fileName) throws IOException { File file = new File(fileName); if (!file.isAbsolute()) { file = new File(location, fileName); } try { fileItem.write(file); } catch (Exception e) { throw new IOException(e); } }
这时候咱们看到若是file.isAbsolute()
成立,也就是咱们没有使用绝对路径,那么file = new File(location,fileName);
会在原来的基础上加上location路径.这就是缘由所在,能够经过修改绝对路径解决web
在代码中控制spring
@PostMapping("/upload") public Map<String, String> upload(@RequestParam MultipartFile file) throws IOException { //建立本地文件 String classpath = ResourceUtils.getURL("classpath:").getPath(); File localFile = new File(classpath + path, file.getOriginalFilename()); //把传上来的文件写到本地文件 file.transferTo(localFile); //返回localFile文件路径 Map<String, String> path = new HashMap<>(); path.put("path", localFile.getAbsolutePath()); return path; }
经过ResourceUtils.getURL("classpath:").getPath()
得到项目路径,而后加上设置的相对路径。json
网络上还有一种修改location
值的方式,能够看 这篇博客可是我我的使用是一直不能够。缓存
或者能够不使用transferTo,代码以下tomcat
@PostMapping("/singleFileUpload") public String singleFileUpload(@RequestParam("file") MultipartFile file) throws IOException { byte[] bytes = file.getBytes(); Path filePath = Paths.get(path + file.getOriginalFilename()); Files.write(filePath, bytes); return file.getOriginalFilename(); }
Paths.get
所使用的也是绝对路径,若是您在Windows机器上使用了这种路径(从/开始的路径),那么路径将被解释为相对于当前驱动器,例如springboot
/file/upload/1.txt
而您的项目位于D盘。那么这条路径就会对应这条完整的路径:网络
D:\file\upload\1.txt
为了简便,如下代码均是使用绝对路径。
@PostMapping("/uploads") public Map<String, String> uploads(@RequestParam MultipartFile[] files) throws IOException { StringBuilder sb = new StringBuilder(); Map<String, String> paths = new HashMap<>(); for (MultipartFile file : files) { //建立本地文件 File localFile = new File(path, file.getOriginalFilename()); //把传上来的文件写到本地文件 file.transferTo(localFile); sb.append(localFile.getAbsolutePath()).append(","); paths.put(file.getOriginalFilename(), localFile.getAbsolutePath()); } //返回localFile文件路径 return paths; }
@PostMapping("/uploadsWithForm") public Map<String, String> uploadsWithForm(@RequestParam String tmpString, @RequestParam MultipartFile[] files) throws IOException { StringBuilder sb = new StringBuilder(); Map<String, String> paths = new HashMap<>(); paths.put("tmpString", tmpString); for (MultipartFile file : files) { //建立本地文件 File localFile = new File(path, file.getOriginalFilename()); //把传上来的文件写到本地文件 file.transferTo(localFile); sb.append(localFile.getAbsolutePath()).append(","); paths.put(file.getOriginalFilename(), localFile.getAbsolutePath()); } //返回localFile文件路径 return paths; }
@PostMapping(value = "/uploadsWithJson") public Map<String, String> uploadsWithJson(@RequestPart("files") MultipartFile[] files, @RequestPart("jsonMap") Map<String, Object> jsonMap) throws IOException { StringBuilder sb = new StringBuilder(); Map<String, String> paths = new HashMap<>(); System.out.println(jsonMap); for (MultipartFile file : files) { //建立本地文件 File localFile = new File(path, file.getOriginalFilename()); //把传上来的文件写到本地文件 file.transferTo(localFile); sb.append(localFile.getAbsolutePath()).append(","); paths.put(file.getOriginalFilename(), localFile.getAbsolutePath()); } paths.put("jsonMap", JsonUtils.obj2json(jsonMap)); //返回localFile文件路径 return paths; }
呵呵,很差用对不对。项目抛出了个异常,HttpMediaTypeNotSupportedException
。
WARN o.s.w.s.m.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported]
因此咱们须要添加个转换器类
@Component public class MultipartJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter { /** * Converter for support http request with header Content-Type: multipart/form-data */ public MultipartJackson2HttpMessageConverter(ObjectMapper objectMapper) { super(objectMapper, MediaType.APPLICATION_OCTET_STREAM); } @Override public boolean canWrite(Class<?> clazz, MediaType mediaType) { return false; } @Override public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) { return false; } @Override protected boolean canWrite(MediaType mediaType) { return false; } }
这样就可以识别了
感受把springboot文件上传所能遇到的坑全踩了个变,心累。
若是须要项目代码,能够去个人github中下载;具体代码能够查看file.upload目录