• springMVC文件上传和下载(简单案例)


    这篇文章,我们将来讲一讲SpringMVC如何实现文件的上传操作。

    一、文件上传 🌹

            1、导入相关依赖 

    1. <dependency>
    2. <groupId>commons-fileuploadgroupId>
    3. <artifactId>commons-fileuploadartifactId>
    4. <version>1.3.1version>
    5. dependency>
    6. <dependency>
    7. <groupId>commons-iogroupId>
    8. <artifactId>commons-ioartifactId>
    9. <version>2.4version>
    10. dependency>

            2、准备jsp页面

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    3. "UTF-8">
    4. 上传页面
    5. 文件上传

    6. "addForm" action="upload" method="post" enctype="multipart/form-data">
    7. 选择文件:"file" name="file" width="120px">
    8. "submit" value="上传">
    9. if test="${url!=null}">
    10. "${pageContext.request.contextPath}/images/${url}" height="200px" width="200px" />
    11. if>
    • 截图 

    • 运行结果

            3、编写Controller

    1. package com.cskt.controller;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.RequestMapping;
    4. import org.springframework.web.bind.annotation.RequestMethod;
    5. import org.springframework.web.bind.annotation.RequestParam;
    6. import org.springframework.web.multipart.MultipartFile;
    7. import org.springframework.web.servlet.ModelAndView;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.*;
    11. import java.net.URLEncoder;
    12. /**
    13. * @Description TODO
    14. * @Author Yii_oo
    15. * @CreateDate 2023-08-31 11:04
    16. * @Version 1.0
    17. * @ClassDesc 文件上传和下载
    18. */
    19. @Controller
    20. public class UploadController {
    21. /**
    22. * 文件上传功能
    23. * @param file
    24. * @return
    25. * @throws IOException
    26. */
    27. @RequestMapping(value = "/upload",method = RequestMethod.POST)
    28. public ModelAndView upload(@RequestParam("file")MultipartFile file, HttpServletRequest request ,ModelAndView modelAndView) throws IOException{
    29. // 图片存放文件夹位置 image你想放在项目的哪个文件夹下
    30. String rootPath = request.getSession().getServletContext().getRealPath("images");
    31. // 上传文件的原始名称
    32. String originalFileName = file.getOriginalFilename();
    33. // 新文件名称
    34. File newFile = new File(rootPath + File.separator + File.separator + originalFileName);
    35. // 判断目标文件所在目录是否存在
    36. if (!newFile.getParentFile().exists()) {
    37. //如果目标文件所在目录不存在,则创建父目录
    38. newFile.getParentFile().mkdirs();
    39. }
    40. file.transferTo(newFile);
    41. System.out.println(newFile); //因为newFile是绝对路径,前端的img需要相对路径
    42. String filePath=newFile.toString();
    43. //截取相对路径
    44. String fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
    45. System.out.println(fileName);
    46. modelAndView.addObject("url",fileName);
    47. modelAndView.setViewName("upload");
    48. return modelAndView;
    49. }
    50. /**
    51. * 文件下载功能
    52. * @param request
    53. * @param response
    54. * @throws Exception
    55. */
    56. @RequestMapping("/down")
    57. public void down(HttpServletRequest request, HttpServletResponse response) throws Exception{
    58. String filename = request.getParameter("filename");
    59. System.out.println(filename);
    60. //模拟文件,myfile.txt为需要下载的文件
    61. String fileName = request.getSession().getServletContext().getRealPath("images")+"/"+filename;
    62. //获取输入流
    63. InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
    64. //假如以中文名下载的话
    65. // String filename = "下载文件.txt";
    66. //转码,免得文件名中文乱码
    67. filename = URLEncoder.encode(filename,"UTF-8");
    68. //设置文件下载头
    69. response.addHeader("Content-Disposition", "attachment;filename=" + filename);
    70. //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
    71. response.setContentType("multipart/form-data");
    72. BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    73. int len = 0;
    74. while((len = bis.read()) != -1){
    75. out.write(len);
    76. out.flush();
    77. }
    78. out.close();
    79. }
    80. }

                  4、运行结果

     就完成了!

  • 相关阅读:
    【小程序源码】实用的智力测试小游戏
    设计模式学习笔记(十五)命令模式及在Spring JdbcTemplate 中的实现
    <前端>Electron-builder为公证后的app打更新信息latest.yml
    「运维有小邓」如何更有效的避免密码攻击
    从Spring源码探究SpringMVC运行流程
    Flask学习笔记(七)
    在线订餐管理系统
    python操作kafka
    rabbitmq消费端auto和manual区别;处理mq的requeue
    数字驱动,营销赋能丨工商职院电子商务专业学生,前往餐饮美食电商新业态基地试岗交流
  • 原文地址:https://blog.csdn.net/2301_78163113/article/details/132606129