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

    你可能感兴趣的文章
    oracle零碎要点---ip地址问题,服务问题,系统默认密码问题
    查看>>
    oracle零碎要点---oracle em的web访问地址忘了
    查看>>
    Oracle零碎要点---多表联合查询,收集数据库基本资料
    查看>>
    Oracle静默安装
    查看>>
    Oracle面试题:Oracle中truncate和delete的区别
    查看>>
    ThreadLocal线程内部存储类
    查看>>
    thinkphp 常用SQL执行语句总结
    查看>>
    Oracle:ORA-00911: 无效字符
    查看>>
    Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
    查看>>
    TCP基本入门-简单认识一下什么是TCP
    查看>>
    tableviewcell 中使用autolayout自适应高度
    查看>>
    Orcale表被锁
    查看>>
    svn访问报错500
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>