博客
关于我
SpringMVC(16)——文件下载
阅读量:250 次
发布时间:2019-03-01

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

Spring MVC 文件上传与下载实现

1. 文件上传

1.1 创建 controller 类

package controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;@Controllerpublic class FileDownController {    @RequestMapping("/showDownFiles")    public String showDownFiles(HttpServletRequest request, Model model) {        String realPath = request.getServletContext().getRealPath("/fileUpload/temp/");        File dir = new File(realPath);        File[] files = dir.listFiles();        ArrayList
fileNameList = new ArrayList<>(); for (int i = 0; i < files.length; i++) { fileNameList.add(files[i].getName()); } model.addAttribute("files", fileNameList); return "showDownFiles"; } @RequestMapping("/down") public String down(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response) { try { String filePath = request.getServletContext().getRealPath("/fileUpload/temp/"); response.setHeader("Content-Type", "application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + toUTF8String(filename)); FileInputStream fis = new FileInputStream(filePath + "\\" + filename); ServletOutputStream sos = response.getOutputStream(); byte[] b = new byte[1024]; int aRead = 0; while ((aRead = fis.read(b)) != -1) { sos.write(b, 0, aRead); } sos.flush(); fis.close(); sos.close(); } catch (IOException e) { e.printStackTrace(); } return null; } public String toUTF8String(String str) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 0 && c <= 255) { sb.append(c); } else { try { byte[] b = Character.toString(c).getBytes("UTF-8"); for (int j = 0; j < b.length; j++) { int k = b[j]; if (k < 0) { k = 255; } sb.append("%" + Integer.toHexString(k).toUpperCase()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); sb.append("%" + Integer.toHexString(c)); } } } return sb.toString(); }}

1.2 创建 upload controller 类

package controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.multipart.MultipartFile;import pojo.UploadFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.IOException;import java.util.List;@Controllerpublic class FileUploadController {    @RequestMapping("/upload")    public String upload(@ModelAttribute UploadFile uploadFile, HttpServletRequest request, HttpServletResponse response) {        String realPath = request.getServletContext().getRealPath("/fileUpload/temp/");        File targetDir = new File(realPath);        if (!targetDir.exists()) {            targetDir.mkdirs();        }        List
files = uploadFile.getMyfile(); for (int i = 0; i < files.size(); i++) { MultipartFile multipartFile = files.get(i); String originalFilename = multipartFile.getOriginalFilename(); File targetFile = new File(realPath, originalFilename); try { multipartFile.transferTo(targetFile); } catch (IOException e) { e.printStackTrace(); } } return "success"; }}

1.3 创建 UploadFile 类

package pojo;import org.springframework.web.multipart.MultipartFile;import java.util.List;public class UploadFile {    private List
myfile; public List
getMyfile() { return myfile; } public void setMyfile(List
myfile) { this.myfile = myfile; }}

2. 文件下载

2.1 设置正确的 MIME 类型

response.setHeader("Content-Type", "application/x-msdownload");

2.2 设置正确的 Content-Disposition 头

response.setHeader("Content-Disposition", "attachment; filename=" + toUTF8String(filename));

3. 项目配置

3.1 springmvc-servlet.xml

3.2 web.xml

springmvc
org.springframework.web.servlet.DispatcherServlet
1
springmvc
/
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*

3.3 index.jsp

    
文件上传
选择文件1:
选择文件2:
选择文件3:
选择文件4:
选择文件5:

3.4 showDownFiles.jsp

    下载文件    

3.5 success.jsp

    成功    
  • ${file.originalFilename}

4. 注意事项

  • 确保所有文件都存放在 /fileUpload/temp/ 目录下。
  • 使用 UTF-8 编码来确保文件名的正确显示。
  • 测试时,确保浏览器的字符编码设置为 UTF-8。
  • 如果出现乱码问题,请检查 toUTF8String 方法是否正确。
  • 确保所有配置文件路径正确,避免文件存储位置错误。
  • 5. 运行测试

  • 打开浏览器访问 http://localhost:8080/index.jsp
  • 选择文件并上传。
  • 浏览文件列表并点击下载链接。
  • 测试文件是否正确下载并保存到本地。
  • 通过以上步骤,您应该能够顺利实现文件上传和下载功能。如果有任何问题,请仔细检查配置文件和代码,确保所有设置正确无误。

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

    你可能感兴趣的文章
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>
    npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
    查看>>
    npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
    查看>>
    npm—小记
    查看>>
    npm上传自己的项目
    查看>>
    npm介绍以及常用命令
    查看>>
    NPM使用前设置和升级
    查看>>
    npm入门,这篇就够了
    查看>>
    npm切换到淘宝源
    查看>>
    npm切换源淘宝源的两种方法
    查看>>
    npm前端包管理工具简介---npm工作笔记001
    查看>>
    npm包管理深度探索:从基础到进阶全面教程!
    查看>>
    npm升级以及使用淘宝npm镜像
    查看>>
    npm发布包--所遇到的问题
    查看>>
    npm发布自己的组件UI包(详细步骤,图文并茂)
    查看>>
    npm和package.json那些不为常人所知的小秘密
    查看>>