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

servlet文件下载

时间:2015-02-14 12:24:21      阅读:465      评论:0      收藏:0      [点我收藏+]

标签:servlet   servlet文件下载   filedownload   

servlet的文件下载与文件上传相似。


文件上传时,关键点是form表单的enctype属性值设置为multipart/form-data,旨在告诉服务器,向服务器发送二进制数据;

文件下载时,则是在响应的response.setContentType("application/pdf")方法中设置文件的后缀格式,以及在响应头信息中指明文件的名称response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"")告诉浏览器该如何解析该流文件。


具体看代码

package com.filedownload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

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

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

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String dataDirectory = request.
                getServletContext().getRealPath("/WEB-INF/");
		String filename = "Java Persistence with MyBatis 3.pdf";
        File file = new File(dataDirectory, filename);
        if (file.exists()) {
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", 
                    "attachment; filename=\"" + filename + "\"");
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (IOException ex) {
                System.out.println (ex.toString());
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

代码关键部分为 doGet 方法中的文件获取及response响应的设置

String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/");
String filename = "Java Persistence with MyBatis 3.pdf";
File file = new File(dataDirectory, filename);

这三行代码,获取到要下载的文件

request.getServletContext().getRealPath("/WEB-INF/"); 获取WEB-INF 目录的真实路径,filename 指定要下载的文件的名称

如果要下载的文件不在tomcat的容器内,那么也可以使用绝对路径,指向文件的真实路径

如 File file = new File("d:\\test.pdf");


response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
response.setContentType("application/pdf") 设置文件的mime type ,告诉浏览器,该流文件按照pdf 格式去解析

response.addHeader("Content-Disposition",  "attachment; filename=\"" + filename + "\"");  设置下载时显示的文件名称为 filename 。

为什么这里要转义,防止文件名中的空格将文件名截断


剩下的部分就是将文件流推送到浏览器了,这里就不细述了。




servlet文件下载

标签:servlet   servlet文件下载   filedownload   

原文地址:http://blog.csdn.net/magi1201/article/details/43816245

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