本帖最后由 CrazyProgram 于 2013-5-2 08:53 编辑
- package zhiwei.deng.web.servlet.download;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileInputStream;
- import java.io.IOException;
- 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;
- import zhiwei.deng.web.servlet.util.UploadUtil;
- //将文件下载到本地
- public class DownloadServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String uuidFileName = request.getParameter("uuidFileName");
- byte[] buf = uuidFileName.getBytes("ISO-8859-1");
- uuidFileName = new String(buf, "utf-8");
- int index = uuidFileName.indexOf("_");
- String realFileName = uuidFileName.substring(index+1);
- //response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(realFileName,"UTF-8"));
- response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(realFileName,"utf-8"));
- String uploadPath = this.getServletContext().getRealPath(UploadUtil.uploadPath);
- System.out.println(uploadPath);
- String uuidFilePath = UploadUtil.makeUuidFilePath(uploadPath, uuidFileName);
- System.out.println(uuidFilePath);//-----uuidFilePath没得到正确的
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(uuidFilePath+"/"+uuidFileName));
- BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
- int len=0;
- buf = new byte[1024];
- while((len=bis.read(buf))>0){
- bos.write(buf, 0, len);
- }
- bis.close();
- bos.close();
- }
- }
复制代码- public static String makeUuidFilePath(String uploadPath, String uuidFileName) {
- String uuidFilePath = null;
- int code = uuidFileName.hashCode();//打印文件名的hashcode码,
- int dir1 = code & 0xF;//设置一级目录
- int dir2 = code >> 4 & 0xF;
- File file = new File(uploadPath+"/"+dir1+"/"+dir2);
- if(!file.exists()){
- //如果目录不存在,一次性创建
- file.mkdirs();
- uuidFilePath = file.getPath();
- }else{
- uuidFilePath = file.getPath();
- }
- return uuidFilePath;
- }
复制代码 |