[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 );
// Locate the folder where the file is located
// String savepath = this. getFileSavePath (filename); // The current file name is UUID
String savepath = this. getFileSavePath (this. getRealName (filename ));
File f = new File (savepath + "\" + filename );
If (! F. exists ()){
Request. setAttribute ("message", "the downloaded resource does not exist ");
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 [1, 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 );
}
}