Skip to content

Instantly share code, notes, and snippets.

@zhuhai
Created August 18, 2013 08:26
Show Gist options
  • Save zhuhai/6260560 to your computer and use it in GitHub Desktop.
Save zhuhai/6260560 to your computer and use it in GitHub Desktop.
文件下载
package com.kaishengit.web;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Map<String,String> mimeMap=new HashMap<String, String>();
static{
mimeMap.put("zip", "application/zip");
mimeMap.put("pdf", "application/pdf");
mimeMap.put("jpg", "image/jpeg");
mimeMap.put("png", "image/png");
mimeMap.put("doc", "application/msword");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
File file=new File("E:/upload");
String fileName=request.getParameter("f");
fileName=new String(fileName.getBytes("ISO8859-1"),"UTF-8");
File downloadFile=new File(file,fileName);
if(!downloadFile.exists()){
response.sendError(404);
return;
}
String extName=fileName.substring(fileName.lastIndexOf(".")+1);
//设置文件下载的类型
response.setContentType(mimeMap.get(extName));
//添加对进度条的支持
response.setContentLength(new Long(downloadFile.length()).intValue());
//对被下载文件的中文文件名进行转码操作
fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");
//改变浏览器接收到的文件的名字
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
InputStream inputStream=new FileInputStream(downloadFile);
OutputStream outputStream=response.getOutputStream();
BufferedInputStream bis=new BufferedInputStream(inputStream);
BufferedOutputStream bos=new BufferedOutputStream(outputStream);
byte[] buffer=new byte[4096];
int len=-1;
while((len=bis.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
bos.flush();
bos.close();
bis.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment