• 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>
  • 相关阅读:
    js 遇到问题
    table 排序 添加 删除 等操作
    json对象
    .style, .getComputedStyle(),.currentStyle区别
    3个div 宽度移入移出时变化
    运动 js
    OWASP Top 10之文件上传漏洞简析(二)
    owasp top10 之文件上传漏洞简析
    前台实现ajax 需注意的地方
    apache-Rewrite重写规则配置
  • 原文地址:https://www.cnblogs.com/asenyang/p/15468777.html
Copyright © 2020-2023  润新知