Use JSP to directly download files

Source: Internet
Author: User

<%

// Sometimes the user wants to download the file, but the file type is associated with the browser in the system, and the result is opened in IE.

// Common examples include Word, Excel, and PDF. Therefore, converting a file into a data stream allows the browser to download the file without knowing its file type.

// Example:

// <A href = "Download. jsp? Path = img/&name=test.gif "> download image </a>

String root = getservletcontext (). getrealpath ("/");

String Path = request. getparameter ("path ");

String name = request. getparameter ("name ");

Response. setcontenttype ("unknown ");

// Note: If attachment is removed from the following line of code, ie will automatically open the file.

Response. addheader ("content-disposition", "attachment; filename =/" "+ name + "/"");

Try

{

Java. Io. outputstream OS = response. getoutputstream ();

Java. Io. fileinputstream FCM = new java. Io. fileinputstream (root + path + name );

Byte [] B = new byte [1024];

Int I = 0;

While (I = FCM. Read (B)> 0)

{

OS. Write (B, 0, I );

}

FCM. Close ();

OS. Flush ();

OS. Close ();

}

Catch (exception E)

{}

%>

Related Article

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.