博客
关于我
(六)SpringMVC文件上传和下载(显示一个路径下的所有可下载文件)
阅读量:351 次
发布时间:2019-03-04

本文共 5011 字,大约阅读时间需要 16 分钟。

Spring MVC 文件上传与下载实现指南

1. Demo效果

文件上传和下载功能的演示已完成,具体效果如下:

  • 文件上传:用户可通过选择本地文件并提交,系统会将文件接收并存储至服务器。如图示所示,点击“上传”按钮即可完成操作。
  • 文件下载:系统支持通过链接下载已上传的文件,点击下载链接即可获取文件。如图示所示,文件可通过浏览器直接下载。

2. 特别配置注意事项

配置文件中需特别注意以下几点:

  • 表单编码:文件上传表单的表单编码类型必须设置为“multipart/form-data”,如图所示。
  • 文件接收POJO:POJO类需设置一个代表文件的字段,其类型为MultipartFile,如图所示。
  • SpringMVC配置:需在SpringMVC的核心配置文件中添加MultipartResolver配置,设置上传文件大小和编码方式,确保文件上传功能正常运行,如图所示。

3. 需要的Jar包

完成文件上传和下载功能后,需添加以下Jar包:

  • spring-webmvc:用于Spring MVC框架支持。
  • spring-web:提供Spring的核心功能支持。
  • commons-fileupload:用于文件上传和下载操作。
  • commons-io:提供文件操作相关功能支持。

4. 目录结构

项目目录树如下:

project├── src│   ├── main│   │   ├── java│   │   │   ├── controller│   │   │   └── po│   │   └── webapp│   │       ├── CSS│   │       └── JavaScript│   └── test└── war    └── web.xml

5. 程序架构

系统基于SpringMVC架构,采用MVC模式设计,所有用户请求通过前端控制器映射至相应的控制器方法处理。

6. 具体代码

以下是系统的核心代码实现:

1. Web配置文件(web.xml)
pro4
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-mvc.xml
1
springmvc
/
2. Spring配置文件(spring-mvc.xml)
/WEB-INF/
.jsp
10485760
UTF-8
3. POJO类(User.java)
package po;import org.springframework.web.multipart.MultipartFile;public class User implements Serializable {    private MultipartFile file;    public MultipartFile getFile() {        return file;    }    public void setFile(MultipartFile file) {        this.file = file;    }}
4. 控制器(FileController.java)
package controller;import java.io.File;import javax.servlet.http.HttpServletRequest;import org.apache.commons.io.FileUtils;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import po.User;@Controllerpublic class FileController {    @RequestMapping(value="/upload", method=RequestMethod.POST)    public String upload(HttpServletRequest request, User user, Model model) throws Exception {        if(!user.getFile().isEmpty()) {            String path = request.getSession().getServletContext().getRealPath("/files/");            String filename = user.getFile().getOriginalFilename();            File filepath = new File(path, filename);            if(!filepath.getParentFile().exists()) {                filepath.getParentFile().mkdirs();            }            user.getFile().transferTo(new File(path + File.separator + filename));            model.addAttribute("user", user);            return "downloadFile";        }        return "error";    }    @RequestMapping(value="/downloadd")    public ResponseEntity
download(HttpServletRequest request, @RequestParam("filename") String filename, Model model) throws Exception { String path = request.getSession().getServletContext().getRealPath("/files/"); File file = new File(path + File.separator + filename); HttpHeaders headers = new HttpHeaders(); String downloadFileName = new String(filename.getBytes("UTF-8"), "UTF-8"); headers.setContentDispositionFormData("attachment", downloadFileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } @RequestMapping(value="/upload", method=RequestMethod.GET) public String uploadForm() { return "uploadForm"; }}
5. 视图文件(uploadForm.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> 
文件上传

文件上传

请选择文件:
6. 视图文件(downloadFile.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ page import="java.io.File" %> 
文件下载

文件下载

<% String path = request.getSession().getServletContext().getRealPath("/files/"); File file = new File(path); File[] fs = file.listFiles(); for(File f:fs) { if(!f.isDirectory()) { String filename = f.getName(); out.print(""); out.print(filename); out.print(""); } } %>
7. 错误页面(error.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> 
上传失败

上传失败

以上是Spring MVC文件上传与下载系统的完整实现方案,涵盖了配置、代码和视图实现等方面,能够帮助开发者快速搭建一个功能齐全的文件管理系统。

转载地址:http://ukbh.baihongyu.com/

你可能感兴趣的文章
opencv3-Mat对象
查看>>
opencv30-图像矩
查看>>
opencv32-基于距离变换和分水岭的图像分割
查看>>
opencv4-图像操作
查看>>
opencv5-图像混合
查看>>
opencv6-调整图像亮度和对比度
查看>>
opencv7-绘制形状和文字
查看>>
opencv8-图像模糊
查看>>
opencv9-膨胀和腐蚀
查看>>
OpenCV_ cv2.imshow()
查看>>
opencv_core.dir/objects.a(vs_version.rc.obj)‘ is incompatible with i386:x86-64 output
查看>>
opencv——图像缩放1(resize)
查看>>
opencv——最简单的视频读取
查看>>
Opencv——模块介绍
查看>>
OpenCV与AI深度学习 | 2024年AI初学者需要掌握的热门技能有哪些?
查看>>
OpenCV与AI深度学习 | CIB-SE-YOLOv8: 优化的YOLOv8, 用于施工现场的安全设备实时检测 !
查看>>
OpenCV与AI深度学习 | CoTracker3:用于卓越点跟踪的最新 AI 模型
查看>>
OpenCV与AI深度学习 | OpenCV中八种不同的目标追踪算法
查看>>
OpenCV与AI深度学习 | OpenCV图像拼接--Stitching detailed使用与参数介绍
查看>>
OpenCV与AI深度学习 | OpenCV如何读取仪表中的指针刻度
查看>>