• SpringMvc--文件上传下载


    一.什么是SpringMvc文件上传下载

    二.文件上传

    编写hpjyController类

    编写upload.jsp

    建立一个储存图片的文件夹

    ​编辑 

     编写PageController来处理页面跳转

    编写工具类PropertiesUtil

    编写resource.properties类

    编写list.jsp

     测试结果

    三.文件下载

    编写hpjyController类

    编写list.jsp

     测试结果

    四.jrebel&多文件上传

    下载JRebel插件

    下载好后重启idear

    ​编辑下载好后要先打开代理ReverseProxy_windows_amd64.exe(顺序不能错)

    jrebel项目启动

    注册jrebel

    测试结果

    设置离线状态

    ​编辑 多文件上传

    编写hpjyController类

    编写upload.jsp

    测试结果


    一.什么是SpringMvc文件上传下载

    Spring MVC是一个基于Java的MVC(Model-View-Controller)框架,用于构建Web应用程序。文件上传下载是指在Web应用中将文件从客户端上传到服务器或从服务器下载到客户端的过程。

    在Spring MVC中,文件上传下载可以通过以下几个步骤完成:

    文件上传:

    1. 在表单中设置enctype为"multipart/form-data",以支持文件上传。
    2. 使用MultipartFile接口作为Controller方法的参数,用于接收上传的文件。
    3. 使用MultipartResolver来解析并处理上传的文件。

    文件下载:

    1. 设置正确的响应头信息,包括文件类型(Content-Type)和文件名(Content-Disposition)。
    2. 将文件内容写入响应体中,以便客户端可以下载。

    Spring MVC提供了许多方便的工具和类来简化文件上传下载的过程,例如MultipartFile、MultipartResolver、ResponseEntity等。您可以根据具体的需求,结合这些功能进行文件上传下载的实现。

    二.文件上传

    编写hpjyController类
    1. package com.xy.web;
    2. import com.xy.biz.hpjyBiz;
    3. import com.xy.model.hpjy;
    4. import com.xy.utils.PageBean;
    5. import com.xy.utils.PropertiesUtil;
    6. import org.apache.commons.io.FileUtils;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.web.bind.annotation.GetMapping;
    10. import org.springframework.web.bind.annotation.RequestMapping;
    11. import org.springframework.web.multipart.MultipartFile;
    12. import javax.servlet.http.HttpServletRequest;
    13. import java.io.File;
    14. import java.io.IOException;
    15. import java.util.List;
    16. /**
    17. * @author bing人
    18. * @site
    19. * @company xy集团
    20. * @create 2023-09-08 19:13
    21. */
    22. @Controller
    23. @RequestMapping("/hpjy")
    24. public class hpjyController {
    25. @Autowired
    26. private hpjyBiz hpjyBiz;
    27. //增
    28. @RequestMapping("/add")
    29. public String add(hpjy hpjy){
    30. int i = hpjyBiz.insertSelective(hpjy);
    31. return "redirect:list";
    32. }
    33. //删
    34. @RequestMapping("/del")
    35. public String del(hpjy hpjy){
    36. hpjyBiz.deleteByPrimaryKey(hpjy.getId());
    37. return "redirect:list";
    38. }
    39. //改
    40. @RequestMapping("/edit")
    41. public String edit(hpjy hpjy){
    42. hpjyBiz.updateByPrimaryKeySelective(hpjy);
    43. return "redirect:list";
    44. }
    45. //文件上传
    46. @RequestMapping("/upload")
    47. public String upload(hpjy hpjy,MultipartFile xxx){
    48. try {
    49. //后端可以直接利用MultipartFile类,接收前端传递到后台的文件
    50. //将文件转成流,然后写入服务器(某一个硬盘)
    51. //上传的图片真实存放地址
    52. String dir= PropertiesUtil.getValue("dir");
    53. //网络访问地址
    54. String server= PropertiesUtil.getValue("server");
    55. String filename = xxx.getOriginalFilename();
    56. System.out.println("文件名:"+filename);
    57. System.out.println("文件类别:"+xxx.getContentType());
    58. FileUtils.copyInputStreamToFile(xxx.getInputStream(),new File(dir+filename));
    59. hpjy.setImage(server+filename);
    60. hpjyBiz.updateByPrimaryKeySelective(hpjy);
    61. } catch (IOException e) {
    62. e.printStackTrace();
    63. }
    64. return "redirect:list";
    65. }
    66. //查
    67. @RequestMapping("/list")
    68. public String list(hpjy hpjy, HttpServletRequest request){
    69. PageBean pageBean =new PageBean();
    70. pageBean.setRequest(request);
    71. List hpjies = hpjyBiz.listPager(hpjy, pageBean);
    72. request.setAttribute("lst",hpjies);
    73. request.setAttribute("pageBean",pageBean);
    74. return "hpjy/list";
    75. }
    76. //数据回显
    77. @RequestMapping("/presave")
    78. public String presave(hpjy hpjy,HttpServletRequest request){
    79. if(hpjy != null && hpjy.getId() !=null && hpjy.getId() !=0){
    80. hpjy h = hpjyBiz.selectByPrimaryKey(hpjy.getId());
    81. request.setAttribute("h",h);
    82. }
    83. return "hpjy/edit";
    84. }
    85. }
    编写upload.jsp
    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: 30340
    4. Date: 2023/9/9
    5. Time: 14:05
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. 枪械logo上传
    10. "${ctx}/hpjy/upload" method="post" enctype="multipart/form-data">
    11. "text" name="id" readonly="readonly" value="${param.id}"/>
    12. "file" name="xxx"/>
    13. "submit" value="上传图片"/>
    建立一个储存图片的文件夹
     
     编写PageController来处理页面跳转
    1. package com.xy.web;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.PathVariable;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. /**
    6. * @author bing人
    7. * @site
    8. * @company xy集团
    9. * @create 2023-09-07 14:53
    10. */
    11. //专门用来处理页面跳转
    12. @Controller
    13. public class PageController {
    14. @RequestMapping("/page/{page}")
    15. public String toPage(@PathVariable("page") String page){
    16. return page;
    17. }
    18. @RequestMapping("/page/{Dir}/{page}")
    19. public String toDirPage(@PathVariable("Dir") String dir,
    20. @PathVariable("page") String page){
    21. return dir + "/" + page;
    22. }
    23. }
    编写工具类PropertiesUtil
    1. package com.xy.utils;
    2. import java.io.IOException;
    3. import java.io.InputStream;
    4. import java.util.Properties;
    5. public class PropertiesUtil {
    6. public static String getValue(String key) throws IOException {
    7. Properties p = new Properties();
    8. InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties");
    9. p.load(in);
    10. return p.getProperty(key);
    11. }
    12. }
    编写resource.properties类

    编写list.jsp
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
    4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    5. "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    6. "Content-Type" content="text/html; charset=UTF-8">
    7. href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
    8. rel="stylesheet">
    9. src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js">
    10. 博客列表
    11. "form-inline"
    12. action="${pageContext.request.contextPath }/hpjy/list" method="get">
    13. "form-group mb-2">
    14. "text" class="form-control-plaintext" name="name"
    15. placeholder="请输入枪械名称">
    16. <%--"pagination" value="false" type="hidden">--%>
  • "table table-striped bg-success">
  • var="b" items="${lst }">
  • "col">枪械编号"col">枪械名称"col">枪械属性"col">图片logo"col">操作
    ${b.id }${b.name }${b.type }
  • "${b.image}" style="height: 100px;width: 60px;">
  • "${pageBean }">
  • ${pageBean }
  •  测试结果

    三.文件下载

    编写hpjyController类
    1. package com.xy.web;
    2. import com.xy.biz.hpjyBiz;
    3. import com.xy.model.hpjy;
    4. import com.xy.utils.PageBean;
    5. import com.xy.utils.PropertiesUtil;
    6. import org.apache.commons.io.FileUtils;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.http.HttpHeaders;
    9. import org.springframework.http.HttpStatus;
    10. import org.springframework.http.MediaType;
    11. import org.springframework.http.ResponseEntity;
    12. import org.springframework.stereotype.Controller;
    13. import org.springframework.web.bind.annotation.GetMapping;
    14. import org.springframework.web.bind.annotation.RequestMapping;
    15. import org.springframework.web.multipart.MultipartFile;
    16. import javax.servlet.http.HttpServletRequest;
    17. import java.io.File;
    18. import java.io.IOException;
    19. import java.util.List;
    20. /**
    21. * @author bing人
    22. * @site
    23. * @company xy集团
    24. * @create 2023-09-08 19:13
    25. */
    26. @Controller
    27. @RequestMapping("/hpjy")
    28. public class hpjyController {
    29. @Autowired
    30. private hpjyBiz hpjyBiz;
    31. //增
    32. @RequestMapping("/add")
    33. public String add(hpjy hpjy){
    34. int i = hpjyBiz.insertSelective(hpjy);
    35. return "redirect:list";
    36. }
    37. //删
    38. @RequestMapping("/del")
    39. public String del(hpjy hpjy){
    40. hpjyBiz.deleteByPrimaryKey(hpjy.getId());
    41. return "redirect:list";
    42. }
    43. //改
    44. @RequestMapping("/edit")
    45. public String edit(hpjy hpjy){
    46. hpjyBiz.updateByPrimaryKeySelective(hpjy);
    47. return "redirect:list";
    48. }
    49. //文件上传
    50. @RequestMapping("/upload")
    51. public String upload(hpjy hpjy,MultipartFile xxx){
    52. try {
    53. //后端可以直接利用MultipartFile类,接收前端传递到后台的文件
    54. //将文件转成流,然后写入服务器(某一个硬盘)
    55. //上传的图片真实存放地址
    56. String dir= PropertiesUtil.getValue("dir");
    57. //网络访问地址
    58. String server= PropertiesUtil.getValue("server");
    59. String filename = xxx.getOriginalFilename();
    60. System.out.println("文件名:"+filename);
    61. System.out.println("文件类别:"+xxx.getContentType());
    62. FileUtils.copyInputStreamToFile(xxx.getInputStream(),new File(dir+filename));
    63. hpjy.setImage(server+filename);
    64. hpjyBiz.updateByPrimaryKeySelective(hpjy);
    65. } catch (IOException e) {
    66. e.printStackTrace();
    67. }
    68. return "redirect:list";
    69. }
    70. //查
    71. @RequestMapping("/list")
    72. public String list(hpjy hpjy, HttpServletRequest request){
    73. PageBean pageBean =new PageBean();
    74. pageBean.setRequest(request);
    75. List hpjies = hpjyBiz.listPager(hpjy, pageBean);
    76. request.setAttribute("lst",hpjies);
    77. request.setAttribute("pageBean",pageBean);
    78. return "hpjy/list";
    79. }
    80. //数据回显
    81. @RequestMapping("/presave")
    82. public String presave(hpjy hpjy,HttpServletRequest request){
    83. if(hpjy != null && hpjy.getId() !=null && hpjy.getId() !=0){
    84. hpjy h = hpjyBiz.selectByPrimaryKey(hpjy.getId());
    85. request.setAttribute("h",h);
    86. }
    87. return "hpjy/edit";
    88. }
    89. @RequestMapping(value="/download")
    90. public ResponseEntity<byte[]> download(hpjy hpjy, HttpServletRequest req){
    91. try {
    92. //先根据文件id查询对应图片信息
    93. hpjy h = this.hpjyBiz.selectByPrimaryKey(hpjy.getId());
    94. String diskPath = PropertiesUtil.getValue("dir");
    95. String reqPath = PropertiesUtil.getValue("server");
    96. String realPath = h.getImage().replace(reqPath,diskPath);
    97. String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
    98. //下载关键代码
    99. File file=new File(realPath);
    100. HttpHeaders headers = new HttpHeaders();//http头信息
    101. String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
    102. headers.setContentDispositionFormData("attachment", downloadFileName);
    103. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    104. //MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息
    105. return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    106. }catch (Exception e){
    107. e.printStackTrace();
    108. }
    109. return null;
    110. }
    111. }
    编写list.jsp
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
    4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    5. "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    6. "Content-Type" content="text/html; charset=UTF-8">
    7. href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
    8. rel="stylesheet">
    9. src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js">
    10. 博客列表
    11. "form-inline"
    12. action="${pageContext.request.contextPath }/hpjy/list" method="get">
    13. "form-group mb-2">
    14. "text" class="form-control-plaintext" name="name"
    15. placeholder="请输入枪械名称">
    16. <%--"pagination" value="false" type="hidden">--%>
  • "table table-striped bg-success">
  • var="b" items="${lst }">
  • "col">枪械编号"col">枪械名称"col">枪械属性"col">图片logo"col">操作
    ${b.id }${b.name }${b.type }
  • "${b.image}" style="height: 100px;width: 60px;">
  • "${pageBean }">
  • ${pageBean }
  •  测试结果

    四.jrebel&多文件上传

    下载JRebel插件

    下载好后重启idear
    下载好后要先打开代理ReverseProxy_windows_amd64.exe(顺序不能错)
    jrebel项目启动

    注册jrebel

    测试结果

    (出来了这一行就代表启动成功了)

    设置离线状态

    (没有离线状态)

    离线状态(出先了这两个就是离线状态了)

     多文件上传
    编写hpjyController类
    1. package com.xy.web;
    2. import com.xy.biz.hpjyBiz;
    3. import com.xy.model.hpjy;
    4. import com.xy.utils.PageBean;
    5. import com.xy.utils.PropertiesUtil;
    6. import org.apache.commons.io.FileUtils;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.http.HttpHeaders;
    9. import org.springframework.http.HttpStatus;
    10. import org.springframework.http.MediaType;
    11. import org.springframework.http.ResponseEntity;
    12. import org.springframework.stereotype.Controller;
    13. import org.springframework.web.bind.annotation.GetMapping;
    14. import org.springframework.web.bind.annotation.RequestMapping;
    15. import org.springframework.web.multipart.MultipartFile;
    16. import javax.servlet.http.HttpServletRequest;
    17. import java.io.File;
    18. import java.io.IOException;
    19. import java.util.List;
    20. /**
    21. * @author bing人
    22. * @site
    23. * @company xy集团
    24. * @create 2023-09-08 19:13
    25. */
    26. @Controller
    27. @RequestMapping("/hpjy")
    28. public class hpjyController {
    29. @Autowired
    30. private hpjyBiz hpjyBiz;
    31. //增
    32. @RequestMapping("/add")
    33. public String add(hpjy hpjy){
    34. int i = hpjyBiz.insertSelective(hpjy);
    35. return "redirect:list";
    36. }
    37. //删
    38. @RequestMapping("/del")
    39. public String del(hpjy hpjy){
    40. hpjyBiz.deleteByPrimaryKey(hpjy.getId());
    41. return "redirect:list";
    42. }
    43. //改
    44. @RequestMapping("/edit")
    45. public String edit(hpjy hpjy){
    46. hpjyBiz.updateByPrimaryKeySelective(hpjy);
    47. return "redirect:list";
    48. }
    49. //文件上传
    50. @RequestMapping("/upload")
    51. public String upload(hpjy hpjy,MultipartFile xxx){
    52. try {
    53. //后端可以直接利用MultipartFile类,接收前端传递到后台的文件
    54. //将文件转成流,然后写入服务器(某一个硬盘)
    55. //上传的图片真实存放地址
    56. String dir= PropertiesUtil.getValue("dir");
    57. //网络访问地址
    58. String server= PropertiesUtil.getValue("server");
    59. String filename = xxx.getOriginalFilename();
    60. System.out.println("文件名:"+filename);
    61. System.out.println("文件类别:"+xxx.getContentType());
    62. FileUtils.copyInputStreamToFile(xxx.getInputStream(),new File(dir+filename));
    63. hpjy.setImage(server+filename);
    64. hpjyBiz.updateByPrimaryKeySelective(hpjy);
    65. } catch (IOException e) {
    66. e.printStackTrace();
    67. }
    68. return "redirect:list";
    69. }
    70. //多文件上传
    71. @RequestMapping("/uploads")
    72. public String uploads(HttpServletRequest req, hpjy hpjy, MultipartFile[] files){
    73. try {
    74. StringBuffer sb = new StringBuffer();
    75. for (MultipartFile cfile : files) {
    76. //思路:
    77. //1) 将上传图片保存到服务器中的指定位置
    78. String dir = PropertiesUtil.getValue("dir");
    79. String server = PropertiesUtil.getValue("server");
    80. String filename = cfile.getOriginalFilename();
    81. FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
    82. sb.append(filename).append(",");
    83. }
    84. System.out.println(sb.toString());
    85. } catch (Exception e) {
    86. e.printStackTrace();
    87. }
    88. return "redirect:list";
    89. }
    90. //查
    91. @RequestMapping("/list")
    92. public String list(hpjy hpjy, HttpServletRequest request){
    93. PageBean pageBean =new PageBean();
    94. pageBean.setRequest(request);
    95. List hpjies = hpjyBiz.listPager(hpjy, pageBean);
    96. request.setAttribute("lst",hpjies);
    97. request.setAttribute("pageBean",pageBean);
    98. System.out.println("jrebel active");
    99. return "hpjy/list";
    100. }
    101. //数据回显
    102. @RequestMapping("/presave")
    103. public String presave(hpjy hpjy,HttpServletRequest request){
    104. if(hpjy != null && hpjy.getId() !=null && hpjy.getId() !=0){
    105. hpjy h = hpjyBiz.selectByPrimaryKey(hpjy.getId());
    106. request.setAttribute("h",h);
    107. }
    108. return "hpjy/edit";
    109. }
    110. @RequestMapping(value="/download")
    111. public ResponseEntity<byte[]> download(hpjy hpjy, HttpServletRequest req){
    112. try {
    113. //先根据文件id查询对应图片信息
    114. hpjy h = this.hpjyBiz.selectByPrimaryKey(hpjy.getId());
    115. String diskPath = PropertiesUtil.getValue("dir");
    116. String reqPath = PropertiesUtil.getValue("server");
    117. String realPath = h.getImage().replace(reqPath,diskPath);
    118. String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
    119. //下载关键代码
    120. File file=new File(realPath);
    121. HttpHeaders headers = new HttpHeaders();//http头信息
    122. String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
    123. headers.setContentDispositionFormData("attachment", downloadFileName);
    124. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    125. //MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息
    126. return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    127. }catch (Exception e){
    128. e.printStackTrace();
    129. }
    130. return null;
    131. }
    132. }
    编写upload.jsp
    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: 30340
    4. Date: 2023/9/9
    5. Time: 14:05
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. 枪械logo上传
    10. "${ctx}/hpjy/upload" method="post" enctype="multipart/form-data">
    11. "text" name="id" readonly="readonly" value="${param.id}"/>
    12. "file" name="xxx"/>
    13. "submit" value="上传图片"/>
    14. "post" action="${ctx}/hpjy/uploads" enctype="multipart/form-data">
    15. "file" name="files" multiple>
    测试结果

  • 相关阅读:
    新晋国产证书品牌——JoySSL
    Open3D(C++) 点到平面的ICP算法实现点云精配准
    canal rocketmq
    浅谈以驱动为中心的运维架构
    c语言练习题55:IP 地址⽆效化
    unity mono IL2app ILruntime huatuo
    深度学习--- Xception迁移学习
    JMM内存模型
    课程表系列
    基于安卓android微信小程序宠物交易小程序
  • 原文地址:https://blog.csdn.net/2201_75455485/article/details/132776739