码迷,mamicode.com
首页 > 其他好文 > 详细

filedownload

时间:2016-05-27 18:10:57      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

<?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)。

 

filedownload

标签:

原文地址:http://www.cnblogs.com/giantfoot/p/5535562.html

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