Package response;
Import java. Io. fileinputstream;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. Io. inputstream;
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;
// File Download
Public class responsedemo3 extends httpservlet {
Protected void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
String Path = This. getservletcontext (). getrealpath ("/downloads/th.jpeg ");
String filename = path. substring (path. lastindexof ("\") + 1 );
// Get the download file name
// Response. setheader ("content-disposition", "attachment; filename =" + filename );
// If the downloaded file is a Chinese file, the file name must be URL encoded.
Response. setheader ("content-disposition", "attachment; filename =" + urlencoder. encode (filename, "UTF-8 "));
Inputstream in = NULL;
Outputstream out = NULL;
Try {
In = new fileinputstream (PATH );
Int Len = 0;
Byte [] Buf = new byte [1, 1024];
Out = response. getoutputstream ();
While (LEN = in. Read (BUF ))! =-1 ){
Out. Write (BUF, 0, Len );
}
} Finally {
Try {
If (OUT! = NULL ){
Out. Close ();
}
} Finally {
Try {
If (in! = NULL ){
In. Close ();
}
} Catch (exception e ){
E. printstacktrace ();
}
}
}
}
Protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
Doget (request, response );
}
}