一个简单的http请求附件下载

来源:互联网 发布:员工管理系统数据库 编辑:程序博客网 时间:2024/04/29 07:34

附件的下载有很多种实现,使用servlet可以直接在response的输出流中直接写入文件数据,然后浏览器就会直接提示下载该附件。其中比较重要的是设置http请求的响应头,设置响应头的Content-Type以及Content-disposition,Content-Type可以根据附件的类型来设置,具体可以参考:MIME类型收录主要包含Content-Type的可设定值 文章地址:http://blog.csdn.net/dcqboke/article/details/27319185


下面是一个简单的servlet来实现附件下载功能:

package cn.qing.servlet;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DownLoadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//需要下载的附件,在这里直接获取系统磁盘内的Excel文件File file = new File("D:/sheetTemplate/constructsheet-export-template.xls");String fileName = URLEncoder.encode(file.getName(), "utf-8");//设置支持.xls(Excel)文件下载的contentTyperesponse.setContentType("application/vnd.ms-excel");//设置Content-disposition为attachment(附件),并设置文件名response.setHeader("Content-disposition", "attachment; filename="+fileName);int fileLength = (int)file.length();response.setContentLength(fileLength);InputStream inputStream = new FileInputStream(file);ServletOutputStream outputStream = response.getOutputStream();if(fileLength > 0){byte[] buf = new byte[4096];int count = 0 ;while((count = inputStream.read(buf))!=-1){//将附件信息写入ServletOutputStream中,//请求成功后就会将这个ServletOutputStream作为响应内容返回outputStream.write(buf, 0, count);}}inputStream.close();}}
上面的例子中需要下载的附件直接在系统的磁盘中以文件的形式获取,在项目开发中可能是需要根据数据生成指定文件,然后提供下载功能。

0 0
原创粉丝点击