14 springmvc完成文件下载

本节操作完成了springmvc下的文件下载。

1、环境约束

  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64
  • spring 3.2.18

2、前提约束

3、在java文件夹下创建net.wanho.controller.FileDownloadController.java

package net.wanho.controller;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Controller
public class FileController {
    @RequestMapping("/download")
    public void download(String filename, HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //设置响应流文件进行下载
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
        ServletOutputStream sos = resp.getOutputStream();
        File file = new File("D:/", filename);//这个路径为服务器上的磁盘路径
        byte[] bytes = FileUtils.readFileToByteArray(file);
        sos.write(bytes);
        sos.flush();
        sos.close();
    }

}

注意:这里我们将磁盘路径写死,实际使用中应该是读取配置文件。

4 在webapp文件夹下创建filedownload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="download?filename=wanhe.txt">下载</a>
</body>
</html>

注意:确保在D盘下有wanhe.txt文件,这里我们采用硬编码,实际使用中这里将是动态数据。

5、测试

打开浏览器,输入http://localhost:8088/filedownload.jsp,点击下载按钮,选择保存路径,即可完成测试。
至此,我们完成了springmvc中文件的下载操作并进行了测试。

posted @ 2020-03-23 20:22  张力的程序园  阅读(150)  评论(0)    收藏  举报