使用MultipartFile 做文件上传的功能
MultipartFile
<body> <form enctype="multipart/form-data" method="post" action="/upload"> 文件:<input type="file" name="head_img"/> 姓名:<input type="text" name="name"/> <input type="submit" value="上传"/> </form> </body>
控制器
import net.xdclass.demo.domain.JsonData; 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 javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.UUID; @RestController public class FileController { private static final String filePath = "D:\\IdeaProjects\\xdclass_springboot\\src\\main\\resources\\static\\images\\"; @PostMapping(value = "/upload") public JsonData upload( @RequestParam(value = "head_img") MultipartFile file, HttpServletRequest request) { // 表单的 name="name" 属性 String name = request.getParameter("name"); // 上传的文件名 String filename = file.getOriginalFilename(); String suffixName = filename.substring(filename.lastIndexOf(".")); // 随机生成 filename = UUID.randomUUID() + suffixName; File dest = new File(filePath + filename); try { file.transferTo(dest); return new JsonData(0, dest); } catch (IOException e) { e.printStackTrace(); } return new JsonData(-1, null, "faild to save"); } }
MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)。
{
"code": 0,
"data": "D:\\IdeaProjects\\xdclass_springboot\\src\\main\\resources\\static\\images\\611fbdd7-95c5-4803-8c6f-796cccf6d2be.jpg",
"msg": null
}
查看上传的图片。
http://localhost:8080/images/611fbdd7-95c5-4803-8c6f-796cccf6d2be.jpg
@Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //单个文件最大 factory.setMaxFileSize(DataSize.ofMegabytes(300)); /// 设置总上传数据总大小 factory.setMaxRequestSize(DataSize.ofGigabytes(1)); return factory.createMultipartConfig(); }