ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring MVC学习09--文件下载

2021-10-27 07:01:10  阅读:27  来源: 互联网

标签:name -- Spring 09 IOUtils io import org String


建立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

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有