JSP文件下载

2021-03-31 07:25

阅读:431

标签:获取   http   struct   ret   https   attach   ade   encoding   类型   

下载图片

package org.student.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1设置编码
        request.setCharacterEncoding("utf-8");
        //2获取需要下载的文件名
        String fileName = request.getParameter("fileName");    
        //3下载文件需要设置消息头,目前不能解决下载中文名乱码
        response.addHeader("content-Type","application/octet-stream" );//MIME类型:二进制文件(任意文件)
        response.addHeader("content-Disposition","attachement;filename="+fileName );//fileName包含了文件后缀:abc.txt
        //4.文件的绝对路径
        String realPath = "D:\\studyJspForUpload\\newUpload";
        //5.创建文件对象 
        File file = new File(realPath,fileName);
        if(!file.exists()){
            response.getWriter().write("文件不存在");
            return;
        }
        IOUtils.copy(new FileInputStream(file), response.getOutputStream());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 

JSP文件下载

标签:获取   http   struct   ret   https   attach   ade   encoding   类型   

原文地址:https://www.cnblogs.com/ejwbytshooting/p/12590047.html


评论


亲,登录后才可以留言!