filedownload

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

    <!--可以配置一些Listener 或 Filter 来观察一些对象的生命周期 -->
   
    <servlet>
        <servlet-name>download_servlet</servlet-name>
        <servlet-class>edu.shao.webapp.sample.DownloadServlet</servlet-class>
        <init-param>
            <param-name>fileRoot</param-name>
            <param-value>d:/</param-value>
        </init-param>
        <init-param>
            <param-name>contentType</param-name>
            <param-value>application/octet-stream</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>download_servlet</servlet-name>
        <url-pattern>/download</url-pattern>
    </servlet-mapping>
</web-app>

 

 

 

package edu.shao.webapp.sample;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class DownloadServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;
    public static Logger logger=LogManager.getLogger(DownloadServlet.class);
   
    private String contentType;
    private String enc="UTF-8";
    private String fileRoot;
   
    @Override
    public void init(ServletConfig config) throws ServletException {
        contentType = config.getInitParameter("contentType");
        fileRoot = config.getInitParameter("fileRoot");
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        logger.debug("Do Get Method.");
        String fileName=req.getParameter("fileName");
        String filePath=fileRoot+File.separator+fileName;
       
        File downloadFile=new File(filePath);
        if (downloadFile.exists()) {
            logger.info("File exist");
           
            resp.setContentType(contentType);
            Long length=downloadFile.length();
            resp.setContentLength(length.intValue());
            fileName = URLEncoder.encode(downloadFile.getName(), enc);
            resp.addHeader("Content-Disposition", "attachment; filename=" + fileName);
           
            ServletOutputStream servletOutputStream=resp.getOutputStream();
            FileInputStream fileInputStream=new FileInputStream(downloadFile);
            BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
            int size=0;
            byte[] b=new byte[4096];
            while ((size=bufferedInputStream.read(b))!=-1) {
                logger.info("write to output stream..");
                servletOutputStream.write(b, 0, size);
            }
            servletOutputStream.flush();
            servletOutputStream.close();
            bufferedInputStream.close();
        }else {
            logger.info("File is not exist");
        }
    }

}

 

解释:

1、contentType用于定义用户的浏览器如何显示将要加载的数据,或者如何处理将要加载的数据。如网页的contentType是text/html,jpeg图片的contentType是image/jpeg。如果不知道文件类型,可以设置为二进制流文件 application/octet-stream

2、contentType和fileRoot(待下载文件的目录)通过web.xml配置。

3、resp.setContentType()、resp.setContentLength()、resp.addHeader("Content-Disposition", "attachment; filename=" + fileName); 三个调用设置一些必要的响应报头(reponse header)。

 

转载于:https://www.cnblogs.com/giantfoot/p/5535562.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值