Servlet 实现文件的上传与下载 (六)

2014-11-24 10:14:31 · 作者: · 浏览: 4
super.destroy();
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// request.setCharacterEncoding("UTF-8");
try{
String fileName = request.getParameter("name");
OutputStream outputStream = response.getOutputStream();
//输出文件用的字节数组,每次向输出流发送600个字节
byte b[] = new byte[600];
File fileload = new File(this.fileFolder,fileName);
fileName=encodeFileName(request,fileName);
//客服端使用保存文件的对话框
response.setHeader("Content-disposition", "attachment;filename="+fileName);
//通知客户文件的长度
long fileLength = fileload.length();
String length = String.valueOf(fileLength);
response.setHeader("Content_length", length);
//读取文件,并发送给客服端下载
FileInputStream inputStream = new FileInputStream(fileload);
int n = 0;
while((n=inputStream.read(b))!=-1){
outputStream.write(b,0,n);
}
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
try{
PrintWriter out = response.getWriter();
out.println("下载的文件不存在");
out.flush();
out.close();
}catch(IOException ie){
ie.printStackTrace();
}
}catch(IOException ie){
ie.printStackTrace();
try{
PrintWriter out = response.getWriter();
out.println("下载存在问题");
out.flush();
out.close();
}catch(IOException iex){
iex.printStackTrace();
}
}
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
this.fileFolder = getServletContext().getRealPath("/")+"files/_file";
}
private String encodeFileName(HttpServletRequest request,String fileName){
try{
//IE
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") >0){
fileName=URLEncoder.encode(fileName,"UTF-8");
}else{
fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
}
}catch(Exception ex){
ex.printStackTrace();
}
return fileName;
}
}
[java]
  
 
  
 
  
 
  
 
[java]