• SpringMVC之文件的上传下载(教你如何使用有关SpringMVC知识实现文件上传下载的超详细博客)


    目录

    前言

    一、文件上传

    1. 配置多功能视图解析器(spring-mvc.xml)

    2. 添加文件上传页面(upload.jsp)

    upload.jsp

    3.做硬盘网络路径映射

    4. 编写一个处理页面跳转的类

    PageController.java

     ClazzController.java

    5. 初步模拟上传文件

    6.配置目录的配置文件

    resource.properties

    7. 最终实现文件上传并显示

    二、文件下载

    方法代码

     jsp页面代码

    效果测试

     三、多文件上传

    jsp页面显示代码

    多文件上传方法

     测试多文件上传

     四、扩展(jrebel插件运用)

    安装插件

    打开代理服务器

    jrebel启动项目

     后续注意事项


    前言

            在上一期的博客文章中我们了解学习到了有关SpringMVC框架实现模拟增删改查四大功能实现,今天给大家带来的是SpringMVC实现文件的上传下载功能实现模拟,让我们一起来一探究竟吧。

            在Spring MVC中,文件上传下载是指通过web应用程序上传和下载文件。Spring MVC提供了一些便捷的方式来处理文件上传和下载的流程。在文件上传方面,可以MultipartFile对象来接收和处理客户端上传的文件。而在文件下载方面,可以使用Spring MVC的ResponseEntity和InputStreamResource等类来实现文件下载的功能。

            要进行文件上传,可以通过在控制器方法的参数中声明MultipartFile类型的参数来接收上传的文件,然后通过MultipartFile对象的一些方法(如getOriginalFilename()、getSize()等)可以获取文件的原始名称和大小等信息。接收到文件后,可以将文件保存到指定的位置或进行进一步的处理。

    一、文件上传

    1. 配置多功能视图解析器(spring-mvc.xml)

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:aop="http://www.springframework.org/schema/aop"
    6. xmlns:mvc="http://www.springframework.org/schema/mvc"
    7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    9. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    10. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    11. <context:component-scan base-package="com.yx"/>
    12. <mvc:annotation-driven />
    13. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    14. <property name="viewClass"
    15. value="org.springframework.web.servlet.view.JstlView">property>
    16. <property name="prefix" value="/WEB-INF/jsp/"/>
    17. <property name="suffix" value=".jsp"/>
    18. bean>
    19. <mvc:resources location="/static/" mapping="/static/**"/>
    20. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    21. <property name="defaultEncoding" value="UTF-8">property>
    22. <property name="maxUploadSize" value="52428800">property>
    23. <property name="resolveLazily" value="true"/>
    24. bean>
    25. <aop:aspectj-autoproxy/>
    26. beans>

    主要是添加下面这段代码

    1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    2. <property name="defaultEncoding" value="UTF-8">property>
    3. <property name="maxUploadSize" value="52428800">property>
    4. <property name="resolveLazily" value="true"/>
    5. bean>

    在spring-mvc.xml文件添加之前,在pom.xml也要导入相关的依赖和插件。

    2. 添加文件上传页面(upload.jsp)

    upload.jsp

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: 86158
    4. Date: 2023/9/9
    5. Time: 16:08
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. <html>
    10. <head>
    11. <title>班级logo上传title>
    12. head>
    13. <body>
    14. <form action="${pageContext.request.contextPath }/clz/upload" method="post" enctype="multipart/form-data">
    15. <label>班级编号:label><input type="text" name="cid" readonly="readonly" value="${param.cid}"/><br/>
    16. <label>班级图片:label><input type="file" name="photo"/><br/>
    17. <input type="submit" value="上传图片"/>
    18. form>
    19. body>
    20. html>

    3.做硬盘网络路径映射

    4. 编写一个处理页面跳转的类

    PageController.java

    1. package com.yx.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 君易--鑨
    7. * @site www.yangxin.com
    8. * @company 木易
    9. * @create  2023-09-10 17:03
    10. * 处理页面跳转的
    11. */
    12. @Controller
    13. @RequestMapping("/page")
    14. public class PageController {
    15. @RequestMapping("/page/{page}")
    16. public String toPage(@PathVariable("page") String page){
    17. return page;
    18. }
    19. @RequestMapping("/page/{dir}{page}")
    20. public String toDirPage(@PathVariable("dir") String dir,
    21. @PathVariable("page") String page){
    22. return dir+"/"+page;
    23. }
    24. }

     ClazzController.java

    1. package com.yx.web;
    2. import com.yx.biz.ClazzBiz;
    3. import com.yx.model.Clazz;
    4. import com.yx.utils.PageBean;
    5. import com.yx.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.ui.Model;
    10. import org.springframework.web.bind.annotation.PathVariable;
    11. import org.springframework.web.bind.annotation.RequestMapping;
    12. import org.springframework.web.multipart.MultipartFile;
    13. import javax.servlet.http.HttpServletRequest;
    14. import java.io.File;
    15. import java.io.IOException;
    16. import java.util.List;
    17. /**
    18. * @author 君易--鑨
    19. * @site www.yangxin.com
    20. * @company 木易
    21. * @create  2023-09-09 15:25
    22. */
    23. @Controller
    24. @RequestMapping("/clz")
    25. public class ClazzController {
    26. @Autowired
    27. private ClazzBiz clazzBiz;
    28. // 增
    29. @RequestMapping("/add")
    30. public String add(Clazz Clazz){
    31. int i = clazzBiz.insertSelective(Clazz);
    32. return "redirect:list";
    33. }
    34. // 删
    35. @RequestMapping("/del/{mid}")
    36. public String del(@PathVariable("mid") Integer mid){
    37. int i = clazzBiz.deleteByPrimaryKey(mid);
    38. return "redirect:list";
    39. }
    40. // 改
    41. @RequestMapping("/edit")
    42. public String del(Clazz Clazz){
    43. int i = clazzBiz.updateByPrimaryKeySelective(Clazz);
    44. return "redirect:list";
    45. }
    46. // 文件上传
    47. @RequestMapping("/upload")
    48. public String upload(Clazz clazz,MultipartFile photo){
    49. try {
    50. //上传的图片真实存放地址
    51. String dir= PropertiesUtil.getValue("dir");
    52. //网络服务器访问地址
    53. String server=PropertiesUtil.getValue("server");
    54. String filename = photo.getOriginalFilename();
    55. System.out.println("文件名称:"+filename);
    56. System.out.println("文件类型:"+photo.getContentType());
    57. FileUtils.copyInputStreamToFile(photo.getInputStream(),new File(dir+filename));
    58. clazz.setPic(server+filename);//保存到数据库中
    59. clazzBiz.updateByPrimaryKeySelective(clazz);//调用方法修改
    60. } catch (IOException e) {
    61. e.printStackTrace();
    62. }
    63. return "redirect:list";
    64. }
    65. // 查
    66. @RequestMapping("/list")
    67. public String list(Clazz Clazz, HttpServletRequest request){
    68. // Clazz接口参数
    69. PageBean pageBean=new PageBean();
    70. pageBean.setRequest(request);
    71. List Clazzs = clazzBiz.ListPager(Clazz, pageBean);
    72. request.setAttribute("lst",Clazzs);
    73. request.setAttribute("pageBean",pageBean);
    74. //最终跳转到WEB-IEF/Clazz/list.jsp页面
    75. return "clz/list";
    76. }
    77. // 数据回显
    78. @RequestMapping("/preSave")
    79. public String preSave(Clazz Clazz, Model model){
    80. if (Clazz !=null && Clazz.getCid() !=null && Clazz.getCid() != 0){
    81. Clazz c = clazzBiz.selectByPrimaryKey(Clazz.getCid());
    82. model.addAttribute("c",c);
    83. }
    84. return "clz/edit";
    85. }
    86. }

    5. 初步模拟上传文件

    这只是实现了将选中的文件下载到指定的文件夹中,在数据库中未进行修改数据。

    6.配置目录的配置文件

    resource.properties

    1. dir=D:/photo/upload/
    2. server=/upload/

    7. 最终实现文件上传并显示

    二、文件下载

    方法代码

    1. @RequestMapping(value="/download")
    2. public ResponseEntity<byte[]> download(Clazz clazz,HttpServletRequest req){
    3. try {
    4. //先根据文件id查询对应图片信息
    5. Clazz clz = this.clazzBiz.selectByPrimaryKey(clazz.getCid());
    6. String diskPath = PropertiesUtil.getValue("dir");
    7. String reqPath = PropertiesUtil.getValue("server");
    8. String realPath = clz.getPic().replace(reqPath,diskPath);
    9. String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
    10. //下载关键代码
    11. File file=new File(realPath);
    12. HttpHeaders headers = new HttpHeaders();//http头信息
    13. String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
    14. headers.setContentDispositionFormData("attachment", downloadFileName);
    15. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    16. //MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息
    17. return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    18. }catch (Exception e){
    19. e.printStackTrace();
    20. }
    21. return null;
    22. }

    将文件下载的代码添加到指定的Controller类中

     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. html>
    6. <html>
    7. <head>
    8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    9. <link
    10. href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
    11. rel="stylesheet">
    12. <script
    13. src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js">script>
    14. <title>班级列表title>
    15. <style type="text/css">
    16. .page-item input {
    17. padding: 0;
    18. width: 40px;
    19. height: 100%;
    20. text-align: center;
    21. margin: 0 6px;
    22. }
    23. .page-item input, .page-item b {
    24. line-height: 38px;
    25. float: left;
    26. font-weight: 400;
    27. }
    28. .page-item.go-input {
    29. margin: 0 10px;
    30. }
    31. style>
    32. head>
    33. <body>
    34. <form class="form-inline"
    35. action="${pageContext.request.contextPath }/clz/list" method="post">
    36. <div class="form-group mb-2">
    37. <input type="text" class="form-control-plaintext" name="cname"
    38. placeholder="请输入班级名称">
    39. <%-- <input name="pagination" value="false" type="hidden">--%>
    40. div>
    41. <button type="submit" class="btn btn-primary mb-2">查询button>
    42. <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/clz/preSave">新增a>
    43. form>
    44. <table class="table table-striped ">
    45. <thead>
    46. <tr>
    47. <th scope="col">班级IDth>
    48. <th scope="col">班级名称th>
    49. <th scope="col">教员th>
    50. <th scope="col">图片th>
    51. <th scope="col">操作th>
    52. tr>
    53. thead>
    54. <tbody>
    55. <c:forEach var="b" items="${lst }">
    56. <tr>
    57. <td>${b.cid }td>
    58. <td>${b.cname }td>
    59. <td>${b.cteacher }td>
    60. <td>
    61. <img src="${b.pic}" style="height:100px;width: 60px; ">
    62. td>
    63. <td>
    64. <a href="${pageContext.request.contextPath }/clz/preSave?cid=${b.cid}">修改a>
    65. <a href="${pageContext.request.contextPath }/clz/del/${b.cid}">删除a>
    66. <a href="${pageContext.request.contextPath }/page/clz/upload?cid=${b.cid}">图片上传a>
    67. <a href="${pageContext.request.contextPath }/clz/download?cid=${b.cid}">图片下载a>
    68. td>
    69. tr>
    70. c:forEach>
    71. tbody>
    72. table>
    73. <z:page pageBean="${pageBean }">z:page>
    74. body>
    75. html>

    效果测试

     三、多文件上传

    jsp页面显示代码

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: 86158
    4. Date: 2023/9/9
    5. Time: 16:08
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. <html>
    10. <head>
    11. <title>班级logo上传title>
    12. head>
    13. <body>
    14. <form action="${pageContext.request.contextPath }/clz/upload" method="post" enctype="multipart/form-data">
    15. <label>班级编号:label><input type="text" name="cid" readonly="readonly" value="${param.cid}"/><br/>
    16. <label>班级图片:label><input type="file" name="photo"/><br/>
    17. <input type="submit" value="上传图片"/>
    18. form>
    19. <p>多文件上传p>
    20. <form method="post" action="${pageContext.request.contextPath }/clz/uploads" enctype="multipart/form-data">
    21. <input type="file" name="files" multiple>
    22. <button type="submit">上传button>
    23. form>
    24. body>
    25. html>

    多文件上传方法

    1. @RequestMapping("/uploads")
    2. public String uploads(HttpServletRequest req, Clazz clazz, MultipartFile[] files){
    3. try {
    4. StringBuffer sb = new StringBuffer();
    5. for (MultipartFile cfile : files) {
    6. //思路:
    7. //1) 将上传图片保存到服务器中的指定位置
    8. String dir = PropertiesUtil.getValue("dir");
    9. String server = PropertiesUtil.getValue("server");
    10. String filename = cfile.getOriginalFilename();
    11. FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
    12. sb.append(filename).append(",");
    13. }
    14. System.out.println(sb.toString());
    15. } catch (Exception e) {
    16. e.printStackTrace();
    17. }
    18. return "redirect:list";
    19. }

     测试多文件上传

     这是模拟多文件上传到本地路径,在本地路径的文件夹中会显示该图片。(未进行数据库操作),可根据自己的项目需求进行修改运用,例如在商品的多张图片、药品批量入库等等上。

     四、扩展(jrebel插件运用)

    安装插件

    打开代理服务器

    代理服务器放在上传资源中了。注意先启动代理服务器再运用jrebel实现项目运行。

    jrebel启动项目

     后续注意事项

     本期博客分享到这,希望老铁能够三连一波。

  • 相关阅读:
    最长公共子串
    Java函数式编程
    F - New Year Snowmen
    2023年09月编程语言流行度排名
    【JS】typeof和instanceof的区别是什么?
    数据结构实验
    Leetcode_729_我的日程安排表1_线段树/思维
    Spring Boot+微信小程序_保存微信登录者的个人信息
    剑指 Offer II 031. 最近最少使用缓存
    DT Paint Effects工具(一)
  • 原文地址:https://blog.csdn.net/weixin_74352229/article/details/132776866