博客
关于我
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/

    你可能感兴趣的文章
    Neo4j(2):环境搭建
    查看>>
    Neo私链
    查看>>
    nessus快速安装使用指南(非常详细)零基础入门到精通,收藏这一篇就够了
    查看>>
    Nessus漏洞扫描教程之配置Nessus
    查看>>
    Nest.js 6.0.0 正式版发布,基于 TypeScript 的 Node.js 框架
    查看>>
    NetApp凭借领先的混合云数据与服务把握数字化转型机遇
    查看>>
    NetBeans IDE8.0需要JDK1.7及以上版本
    查看>>
    netcat的端口转发功能的实现
    查看>>
    netfilter应用场景
    查看>>
    netlink2.6.32内核实现源码
    查看>>
    Netpas:不一样的SD-WAN+ 保障网络通讯品质
    查看>>
    NetScaler的常用配置
    查看>>
    netsh advfirewall
    查看>>
    NETSH WINSOCK RESET这条命令的含义和作用?
    查看>>
    Netty WebSocket客户端
    查看>>
    netty 主要组件+黏包半包+rpc框架+源码透析
    查看>>
    Netty 异步任务调度与异步线程池
    查看>>
    Netty中集成Protobuf实现Java对象数据传递
    查看>>
    Netty事件注册机制深入解析
    查看>>
    Netty原理分析及实战(四)-客户端与服务端双向通信
    查看>>