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

    你可能感兴趣的文章
    Nim教程【十二】
    查看>>
    Nim游戏
    查看>>
    NIO ByteBuffer实现原理
    查看>>
    Nio ByteBuffer组件读写指针切换原理与常用方法
    查看>>
    NIO Selector实现原理
    查看>>
    nio 中channel和buffer的基本使用
    查看>>
    NIO三大组件基础知识
    查看>>
    NIO与零拷贝和AIO
    查看>>
    NIO同步网络编程
    查看>>
    NIO基于UDP协议的网络编程
    查看>>
    NIO笔记---上
    查看>>
    NIO蔚来 面试——IP地址你了解多少?
    查看>>
    NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
    查看>>
    NISP国家信息安全水平考试,收藏这一篇就够了
    查看>>
    NIS服务器的配置过程
    查看>>
    Nitrux 3.8 发布!性能全面提升,带来非凡体验
    查看>>
    NiuShop开源商城系统 SQL注入漏洞复现
    查看>>
    NI笔试——大数加法
    查看>>
    NLog 自定义字段 写入 oracle
    查看>>
    NLog类库使用探索——详解配置
    查看>>