其他分享
首页 > 其他分享> > Spring MVC学习09--文件下载

Spring MVC学习09--文件下载

作者:互联网

建立Controller:

 1 package com.yas.controller;
 2 
 3 import org.apache.commons.io.IOUtils;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.RequestParam;
 7 
 8 import javax.servlet.http.HttpServletResponse;
 9 import javax.servlet.http.HttpSession;
10 import java.io.FileInputStream;
11 import java.io.IOException;
12 
13 @Controller
14 @RequestMapping("/download")
15 public class DownloadController {
16 
17     @RequestMapping("/test1")
18     public void test1(@RequestParam("name") String name, HttpSession session, HttpServletResponse response) throws IOException {
19         String realPath = session.getServletContext().getRealPath("/upload");
20         String filePath = realPath + "\\" + name;
21         response.setHeader("content-disposition", "attachment;filename=" + name);
22         IOUtils.copy(new FileInputStream(filePath), response.getOutputStream());
23     }
24 }

IOUtils,所在的包是org.apache.commons.io.IOUtils,在上一篇文章中,已经在pom文件中添加了此依赖。

建立测试jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="${pageContext.request.contextPath}/download/test1?name=readme.txt">下载</a>
</body>
</html>

 

标签:name,--,Spring,09,IOUtils,io,import,org,String
来源: https://www.cnblogs.com/asenyang/p/15468777.html