经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » HTML5 » 查看文章
SpringBoot实现文件/图片的上传与下载
来源:cnblogs  作者:風青宇  时间:2021/3/1 9:12:45  对本文有异议
  • 导入依赖(pom.xml)

  1.     <!-- 上传下载需要设计到的jar包 -->
  2. <dependency>
  3. <groupId>commons-io</groupId>
  4. <artifactId>commons-io</artifactId>
  5. <version>2.6</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>commons-fileupload</groupId>
  9. <artifactId>commons-fileupload</artifactId>
  10. <version>1.3.3</version>
  11. </dependency>
  12. <!--servlet-api导入高版本的-->
  13. <dependency>
  14. <groupId>javax.servlet</groupId>
  15. <artifactId>javax.servlet-api</artifactId>
  16. <version>4.0.1</version>
  17. </dependency>
  18. <!-- 图片处理类 -->
  19. <dependency>
  20. <groupId>net.coobird</groupId>
  21. <artifactId>thumbnailator</artifactId>
  22. <version>0.4.8</version>
  23. </dependency>
  • 全局配置 application.properties

  1. # 上传文件大小
  2. spring.servlet.multipart.max-file-size=5MB
  3. spring.servlet.multipart.max-request-size=5MB
  • 创建 WebMvcConfig 配置类  静态资源映射

  1. @Configuration
  2. public class WebMvcConfig implements WebMvcConfigurer {
  3. @Override
  4. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  5. ApplicationHome h = new ApplicationHome(getClass());
  6. File jarF = h.getSource();
  7. String dirPath = jarF.getParentFile().toString()+"/upload/";
  8. String os = System.getProperty("os.name");
  9. if (os.toLowerCase().startsWith("win")) { //如果是Windows系统
  10. registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
  11. } else {
  12. registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
  13. }
  14. }
  15. }
  • 文件或图片上传

  • 控制层
  1. // 上传文件
  2. @ResponseBody
  3. @RequestMapping("/upload")
  4. public String fileUpload(@RequestParam("files") MultipartFile files) throws IOException {
  5. // // win系统 上传路径保存设置
  6. // // 获取项目路径
  7. // File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
  8. // // 绝对路径=项目路径+自定义路径
  9. // File pathFile = new File(projectPath.getAbsolutePath(), "static/upload/");
  10. // if (!pathFile.exists()) {
  11. // pathFile.mkdirs();
  12. // }
  13. // //上传文件地址
  14. // UUID uuid = UUID.randomUUID();
  15. // File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
  16. // files.transferTo(serverFile);
  17. //
  18. // String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");
  19. //
  20. // return imgPath;
  21. // Linux服务器 上传路径保存设置
  22. // 项目路径 /home/www/
  23. File pathFile = new File("/home/www/upload/");
  24. if (!pathFile.exists()) {
  25. pathFile.mkdirs();
  26. }
  27. //上传文件地址
  28. UUID uuid = UUID.randomUUID();
  29. File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
  30. files.transferTo(serverFile);
  31. String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");
  32. return imgPath;
  33. }
  • HTML页面    Ajax 无刷新上传 

  1. <form action="" class="layui-form" enctype="multipart/form-data" method="post">
  2.   <input type="hidden" name="blogImg" id="imgPath" value="">
  3.   <div class="form-group">
  4.     <label>图片上传</label>
  5.     <input type='file' style='margin: 5px;' name='files' required><br>
  6.     <button type="button" class="layui-btn" id="img_upload">上传图片</button>
  7.   </div>
  8.   <input type="submit">
  9. </form>
  • JS

  1. //普通图片上传
  2. $('#img_upload').click(function () {
  3. var formData = new FormData();
  4. //获取选择的文件
  5. $.each($('input[name="files"]'),function (index,item) {
  6. formData.append("files",item.files[0])
  7. });
  8. //发送异步请求
  9. $.ajax({
  10. method:'post',
  11. url: '[[@{/user/upload}]]', // 文件上传接口
  12. data:formData,
  13. processData: false,
  14. contentType:false,
  15. success:function (data) {
  16. //成功返回触发的方法
  17. $('#imgPath').val(data);
  18. alert("上传成功");
  19. },
  20. //请求失败触发的方法
  21. error:function () {
  22. alert("上传失败");
  23. }
  24. });
  25. });
  • 文件或图片下载

  • 控制层
  1. @RequestMapping(value="/download")
  2. public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
  3. //要下载的图片地址
  4. String path = request.getServletContext().getRealPath("/upload");
  5. String fileName = "基础语法.jpg";
  6. //1、设置response 响应头
  7. response.reset(); //设置页面不缓存,清空buffer
  8. response.setCharacterEncoding("UTF-8"); //字符编码
  9. response.setContentType("multipart/form-data"); //二进制传输数据
  10. //设置响应头
  11. response.setHeader("Content-Disposition",
  12. "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
  13. File file = new File(path,fileName);
  14. //2、 读取文件--输入流
  15. InputStream input=new FileInputStream(file);
  16. //3、 写出文件--输出流
  17. OutputStream out = response.getOutputStream();
  18. byte[] buff =new byte[1024];
  19. int index=0;
  20. //4、执行 写出操作
  21. while((index= input.read(buff))!= -1){
  22. out.write(buff, 0, index);
  23. out.flush();
  24. }
  25. out.close();
  26. input.close();
  27. return null;
  28. }
  • HTML页面  

  1. <a href="/download">点击下载</a>

 

 

参考资料:狂神说SpringMVC:文件上传下载

本文网址:https://www.cnblogs.com/dmflysky/p/14450015.html

原文链接:http://www.cnblogs.com/dmflysky/p/14450015.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号