Java Web download URLConnection

Source: Internet
Author: User

Recently in the project to see some information about uploading and downloading, after the test passed, save a spare

String filename = request.getparameter ("filename");
FileName is the path to the file resource,
Integer num = Filename.lastindexof (".");
Get the format of a file
String fileType = "";
if (num>0) {
FileType = filename.substring (num+1, Filename.length ());
}else{
FileType = "png";
}

Response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode ("mz" +filetype, "UTF-8"));
Response.setcontenttype ("Application/octet-stream");
URL url = new URL (filename);
Open connection
URLConnection con = url.openconnection ();
Con.setconnecttimeout (2000);
Con.setdefaultusecaches (FALSE);
SYSTEM.OUT.PRINTLN ("open link");
Input stream
InputStream is = Con.getinputstream ();

1K of data buffering
Byte[] bs = new byte[1024];
Length of data read
int Len;
The output file stream
OutputStream OS = Response.getoutputstream ();
Start reading
while (len = Is.read (BS))! =-1) {
Os.write (BS, 0, Len);
}
Complete, close all links
Os.close ();
Is.close ();
System.out.println ("Download done ..............) ");

Java Web download URLConnection

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.