当前位置:   article > 正文

SpringBoot实现文件上传功能

springboot实现文件上传

大家使用spring-mvc来实现文件上传已经很简单了,其实spring这个团队非常的伟大,为什么这么说呢,使用spring-boot来实现文件上传功能更加的方便快捷,

废话不多上直接上代码

首先需要创建spring-boot项目这点都不用说,不会创建的建议搭建可以先学一下怎么来创建springboot项目。

由于只是实现一个简单的上传功能,所以在这里我就不在使用模板引擎了,直接在static静态文件中创建一个upload.html文件,访问静态文件来操作。

代码如下

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>单文件上传</title>
  6. </head>
  7. <body>
  8. <form action="/upload" method="post" enctype="multipart/form-data">
  9. <input type="file" name="uploadFile" value="请选择文件">
  10. <input type="submit" value="上传">
  11. </form>
  12. </body>
  13. </html>

重要的事情说三遍,在“form”表单中一定要加上“enctype="multipart/form-data"这句话。否则你后端代码是获取不到上传的文件的,关于为什么这样做,不知道的朋友们可以学习一下HTML的知识

接下来呢需要创建一个文件上传的控制类,用来处理上传的文件:

  1. package com.fyn.springboot.upload.controller;
  2. import org.springframework.web.bind.annotation.PostMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. import org.springframework.web.multipart.MultipartFile;
  5. import javax.servlet.http.HttpServletRequest;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Date;
  10. import java.util.UUID;
  11. @RestController
  12. public class FileUpload {
  13. SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
  14. @PostMapping("/upload")
  15. public String upload(MultipartFile uploadFile, HttpServletRequest req){
  16. String realPath = req.getSession().getServletContext().getRealPath("/uploadFile");
  17. String format = sd.format(new Date());
  18. File file = new File(realPath + format);
  19. if (!file.isDirectory()){
  20. file.mkdirs();
  21. }
  22. String oldName = uploadFile.getOriginalFilename();
  23. String newName = UUID.randomUUID().toString() + oldName.substring(oldName.indexOf("."), oldName.length());
  24. try {
  25. uploadFile.transferTo(new File(file,newName));
  26. String path = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + format + newName;
  27. return path;
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. return "上传失败";
  32. }
  33. }

接下来访问127.0.0.1:8080/upload.html就会出现之前写的文件上传页面!

springboot文件上传页面

点击选择文件上传,后会返回对应的文件存储路径地址

springboot文件上传路径

此时可以复制路径,浏览器访问,查看上传结果!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/902191
推荐阅读
相关标签
  

闽ICP备14008679号