package com.shxt.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
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 {
response.setContentType("application/x-msdownload");
PrintWriter out = response.getWriter();
response.reset();// 可以加也可以不加
response.setContentType("application/x-download");
String filedownload = request.getRealPath("/images")
+ "\\02_开发第一个无状态会话bean.avi";// "想办法找到要提供下载的文件的物理路径+文件名";
System.out.print(filedownload);
String filedisplay = "okokok.avi";// "给用户提供的下载文件名";
filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filedisplay);
OutputStream outp = null;
FileInputStream in = null;
try {
outp = response.getOutputStream();
// 你可以指定你的ftp输入流
in = new FileInputStream(new File(filedownload));
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) > 0) {
outp.write(b, 0, i);
}
outp.flush();
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {
if (in != null) {
in.close();
in = null;
}
if (outp != null) {
outp.close();
outp = null;
}
//out.clear();
//out = pageContext.pushBody();
}
}
}