Servlet for downloading files (very simple)

Source: Internet
Author: User
Tags readline save file
servlet| download Import java.io.*;
Import java.util.*;
Import javax.servlet.*;
Import javax.servlet.http.*;

public class Download extends HttpServlet
{
public void doget (HttpServletRequest request, httpservletresponse response) throws IOException, Servletexception
{
Try
{
There's something else you can do.

Response.setcontenttype ("Application/octet-stream");
Response.setheader ("Content-disposition", "attachment; Filename=\ "The Save file name you want to display in the Save Window \");

Servletoutputstream out = Response.getoutputstream ();
BufferedReader br=new BufferedReader (new FileReader (file name to be downloaded));

String Line=br.readline ();
while (Line!=null)
{
Out.write (Line.getbytes ());
Out.println ();
Line=br.readline ();
}
Out.close ();
Br.close ();
}
catch (Exception e)
{
System.out.println (e);
}
}
public void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException, Servletexception
{
Doget (request, response);
}
}
It's so simple.

Moderator Tips:
The code here is a problem when doing a binary file download, because the BufferedReader is used here, and this class is prepared for reading "characters" and needs to be read by "byte", please use InputStream.

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.