J2ee,jsp,servlet File Download server side

Source: Internet
Author: User

1.getOutputStream () have already been called for this response

Reasons for the error:

Only binary files can be written using the Tomcat container when invoking the Response.getoutputstream () method.

But when you call the Requonse.getwriter () method, you can only print text files in the foreground.

So:

If you are on a JSP page:

Outputstream.flush (); Outputstream.close (); Outputstream=null;response.flushbuffer (); Out.clear (); out = Pagecontext.pushbody ();
Here out and PageContext are the built-in objects of JSP;


If in the background:

If you use Response.getwrter, you can only use Response.setcontenttype ("text/html") in front;

If you want to output binary streams, then it is not enough to use response.setcontenttype ("text/html");

If you want to transfer files, it is recommended that:

Response.setcontenttype ("Application/x-msdownload;charset=utf-8");

At the same time in order to prevent garbled, response.setcharacterencoding ("Utf-8");

filename = urlencoder.encode (filename, "utf-8");


Code for file Download:

public void Getdownloadbook () throws Ioexception{response.setcharacterencoding ("Utf-8"); String filepath=request.getsession (). Getservletcontext (). Getrealpath ("\ \") + "upload\\books\\";//through the foreground bookid, Remove the file from the database save Information Book Book=this.getbookservice (). GetBook (BookId), if (book==null) {Response.setcontenttype ("text/html "); PrintWriter writer=response.getwriter (); Writer.write ("


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

J2ee,jsp,servlet File Download server side

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.