servlet for file download

Source: Internet
Author: User
Tags http post
servlet| download//File Download servlet

Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;

public class DownloadFile extends HttpServlet {
private static final String Content_Type = "text/html;" CHARSET=GBK ";
Initialize Global Variables
public void Init () throws Servletexception {
}
Process the HTTP Post request
public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Response.setcontenttype (Content_Type);

String pathsavefile;//the file to download
String filename;//The file name displayed in the Save window
Filename=response.encodeurl (New String (Filename.getbytes (), "iso8859_1"))//transcoding

Try
{
Response.reset ();
Response.setcontenttype ("Application/octet-stream");
Response.setheader ("Content-disposition", "attachment; Filename=\ "" "+filename+" "" ");
Servletoutputstream out = Response.getoutputstream ();
InputStream instream=new FileInputStream (pathsavefile);
Loop out the data in the stream
Byte[] B = new byte[1024];
int Len;
while ((Len=instream.read (b)) >0)
Out.write (B,0,len);
}
Out.close ();
Instream.close ();
}
catch (Exception e)
{
System.out.println (e);
}

}
Clean up resources
public void Destroy () {
}
}



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.