码迷,mamicode.com
首页 > 编程语言 > 详细

javaweb下载文件模板

时间:2017-09-05 20:56:08      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:获取文件的绝对路径   generate   content   http   let   pre   ted   puts   文件名   

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

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

/**
* Servlet implementation class DownloadServlet
*/
public class DownloadServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取需要下载文件名称
String filename = request.getParameter("filename");
//获取下载的类型
response.setContentType(this.getServletContext().getMimeType(filename));
//告知客户端需要下载
response.setHeader("Content-Disposition", "attachment;filename="+filename);
//获取文件的绝对路径
String path = this.getServletContext().getRealPath("download/"+filename);
//获取文件的输入源
InputStream in = new FileInputStream(path);
//获取输出流
ServletOutputStream out = response.getOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len=in.read(buffer))>0) {
out.write(buffer,0,len);
}
in.close();
out.close();
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}

 

javaweb下载文件模板

标签:获取文件的绝对路径   generate   content   http   let   pre   ted   puts   文件名   

原文地址:http://www.cnblogs.com/sangewuxie/p/7481688.html

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