基础 jsp + Servlet 进行文件下载

 

          直接给你能用的代码 

      

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>文件下载基础</title>
</head>
<body>
<form method="post" action="/RTServler">
    下载测试<input type="text" name="name">
    <input type="submit" value="开始下载">

</form>
</body>
</html>

      

     String path = getServletContext().getRealPath("/img/"+name);   本地路径,我就不说了   
package cn.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * Created by ***** on 2018/4/3.
 */
public class RTServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        response.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");//获取要下载的文件名
        System.out.println(name);
        //第一步:设置响应类型
       // response.setContentType("application/force-download");//应用程序强制下载
        //第二读取文件
        String path = getServletContext().getRealPath("/img/"+name);
        System.out.println(path);
        System.out.println("STOP");
        InputStream in = new FileInputStream(path);
        //设置响应头,对文件进行url编码
        name = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+name);
        response.setContentLength(in.available());

        //第三步:老套路,开始copy
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len = in.read(b))!=-1){
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();





    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request,response);
    }
}

 

posted on 2018-04-03 22:11  LWJDD  阅读(119)  评论(0编辑  收藏  举报

导航