黑马程序员技术交流社区
标题:
学习心得
[打印本页]
作者:
lty123
时间:
2019-4-25 08:45
标题:
学习心得
@WebServlet("/DownloadServlet02")
public class DownloadServlet02 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取文件名称
String filename = request.getParameter("filename");
//获取ServletContext域对象
ServletContext servletContext = this.getServletContext();
//获取文件的路径
String realPath = servletContext.getRealPath("/img/" + filename);
//输入流读取文件
FileInputStream fis = new FileInputStream(realPath);
//获取文件的类型
String mimeType = servletContext.getMimeType(filename);
//设置content-type
response.setHeader("content-type",mimeType);
//防乱码
String agent = request.getHeader("user-agent");
filename = DownLoadUtils.getFileName(agent, filename);
//设置将文件作为附件加载
response.setHeader("content-disposition","attachment;filename="+filename);
//写出文件
ServletOutputStream ops = response.getOutputStream();
byte[] buff = new byte[1024*5];
int len=0;
while((len=fis.read(buff))!=-1){
ops.write(buff,0,len);
}
fis.close();
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2