1、首先需要在配置中指定文件的上传路径,先说一下springboot默认的访问文件夹
默认情况下Spring Boot 使用WebMvcAutoConfiguration中配置的各种属性。
默认映射的文件夹有:
classpath:/META-INF/resources
classpath:/resources
classpath:/static
classpath:/public
上面这几个都是静态资源的映射路径,优先级顺序为:META-INF/resources > resources > static > public
2、上传文件,肯定是需要存储在某个外部文件夹中,不能存储在项目中,所以需要指定外部文件夹
upload-path=D:/supload/ spring.resources.static-locations=classpath:/METAINF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${upload-path}
3、由于springboot默认提供了访问文件夹,我将新建的html文件放在了static里面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form enctype="multipart/form-data" method="post" action="/testupload"> 图片<input type="file" name="file"/> <input type="submit" value="上传"/> </form> </body> </html>
4、上传文件代码
package com.example.springdemo.hello; import org.apache.commons.io.FileUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.util.UUID; @RestController public class UploadController { @PostMapping(value="/testupload") public void uploadFile(@RequestParam(name = "file") MultipartFile file){ //判断文件是否为空 if (!file.isEmpty()) { String originFileName = file.getOriginalFilename(); //文件后缀名 String ext= originFileName.substring(originFileName.lastIndexOf(".")+1); //重命名文件 String targetFileName = UUID.randomUUID().toString() + "."+ext; //文件存储文件夹 String parentPath = "D:/supload/"; //实际开发中从配置文件中读取 File parentDir = new File(parentPath); if (!parentDir.exists()) { parentDir.mkdirs(); } File target = new File(parentDir.getAbsolutePath(), targetFileName); try { //file.transferTo(target); // fix weblogic write file bug FileUtils.writeByteArrayToFile(target, file.getBytes()); } catch (Exception e) { } } } }
5、将项目打成jar包
6、运行jar包
上传文件
访问文件