黑马程序员技术交流社区
标题:
下载时取不到uuid的路径,
[打印本页]
作者:
CrazyProgram
时间:
2013-4-19 09:48
标题:
下载时取不到uuid的路径,
本帖最后由 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;
}
复制代码
作者:
刘沛霞
时间:
2013-5-1 09:12
打断点走一下代码,有可能是中文编码问题,查看一下jsp页面的编码,如果页面与servlet的编码不一致,会出现中文乱码问题。
作者:
CrazyProgram
时间:
2013-5-2 08:52
刘沛霞 发表于 2013-5-1 09:12
打断点走一下代码,有可能是中文编码问题,查看一下jsp页面的编码,如果页面与servlet的编码不一致,会出现 ...
唉,好辛苦,一句一句通读了一遍。。。还好算是搞定了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2