Servletresponse File Download

Source: Internet
Author: User

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 );
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.