码迷,mamicode.com
首页 > Web开发 > 详细

JSP文件下载

时间:2020-03-28 23:20:06      阅读:116      评论:0      收藏:0      [点我收藏+]

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

<a href="DownloadServlet?fileName=殷志源03.jpg">下载图片</a>

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!