Listfiles.jsp-----DownloaServlet.java
[java]
package com.hbsi.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
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 {
String filename = request.getParameter("filename");
filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
System.out.println(filename);
//找到该文件所在的文件夹位置
//String savepath = this.getFileSavePath(filename); //现在的文件名是UUID
String savepath = this.getFileSavePath(this.getRealName(filename));
File f = new File(savepath+"\\"+filename);
if(!f.exists()){
request.setAttribute("message","下载的资源不存在");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(this.getRealName(filename),"UTF-8"));
FileInputStream in = new FileInputStream(f);
byte[] buf = new byte[1024];
int len=0;
OutputStream out = response.getOutputStream();
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
in.close();
}
public String getFileSavePath(String filename){
int dir1 = filename.hashCode()&0xf;
int dir2 = (filename.hashCode()>>4)&0xf;
String savepath = this.getServletContext().getRealPath("/WEB-INF/upload")+"\\"+dir1+"\\"+dir2;
return savepath;
}
public String getRealName(String filename){
String realName = filename.substring(filename.indexOf("_")+1);
return realName;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
补充:软件开发 , Java ,