Java File download

Source: Internet
Author: User

File download, either a POST request or a GET request.

Create a new Web project and build the up directory under Webroot to hold the uploaded files:

The simplest but not the actual download method, directly with a tag to the file directory, you can download:

<ahref= "<c:url value= '/up/a.jpg '/>">Download jpg</a>    <BR/>    <ahref= "<c:url value= '/up/cos.jar '/>">Download jar</a>    <BR/>    <ahref= "<c:url value= '/up/db.doc '/>">Download doc</a>     <BR/>     <ahref= "<c:url value= '/up/jingyesi.txt '/>">Download txt</a>      <BR/>    <ahref= "<c:url value= '/up/buystatus.xlsx '/>">Download Excel</a> 

This can be downloaded, but anyone can download, you can't do some control, such as only the user can download the login, not enough people can not download, and, this is problematic, if the downloaded file browser can directly parse, will not be downloaded as an attachment, the browser will open directly, tablets, txt text, If it is in IE browser, if the machine installed Office,ie will also let you choose whether to open the file or download the file:

The average person never does this, it has to be downloaded through a servlet, so you can control the download conditions you want to control:

 PackageCom.lhy.upload;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.URLEncoder;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** File download can be either a GET request or a post *@authorAdministrator **/@WebServlet (Name= "Downservlet", urlpatterns= "/downservlet") Public classDownservletextendshttpservlet{@Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doPost (req, resp); } @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {req.setcharacterencoding ("UTF-8"); String name= Req.getparameter ("name");//get the file name to download//First step: Set the response typeResp.setcontenttype ("Application/force-download");//Application Force Download//Second Read fileString path = Getservletcontext (). Getrealpath ("/up/" +name); InputStream in=NewFileInputStream (path); //set the response header to URL encode the fileName = Urlencoder.encode (name, "UTF-8")); Resp.setheader ("Content-disposition", "attachment;filename=" +name);        Resp.setcontentlength (In.available ()); //step Three: The old routine, start copyOutputStream out =Resp.getoutputstream (); byte[] B =New byte[1024]; intLen = 0;  while(len = In.read (b))!=-1) {Out.write (b,0, Len);    } out.flush ();    Out.close ();  In.close (); }}

Note: Resp.setcontenttype ("application/force-download");//Application Forced download

Previously also did download Word,excel, online said this content-type set this setting that, remember at that time to download Excel, Word also out this problem, go also to Baidu Modify this content-type, not the same file type set not the same, All do not need, here only set to Application/force-download, very steward, no matter what file, whether you are word,excel or what, all the honest to me to download.

There are also Resp.setheader ("Content-disposition", "attachment;filename=" +name); This attachment meaning is the attachment, that is, if the browser can directly parse the file, than the film, you also honestly to the attachment form to me to download, do not give me direct analysis (ie, IE will also prompt you to let you choose to open or download).

Some notes on the Web:

Content-disposition is an extension of the MIME protocol, and the MIME protocol indicates how the MIME user agent displays additional files. Content-disposition can actually control when the user requests the content to save as a file, provide a default file name, the file is displayed directly in the browser or the File Download dialog box when accessed.

Format Description:
Content-disposition = "Content-disposition" ":" Disposition-type * (";" Disposition-parm)

Field Description:
Content-disposition is a property name
How Disposition-type is downloaded, such as attachment for download by attachment
Disposition-parm is the file name when it is saved by default
When the server sends a file to the client browser, if it is a file type supported by the browsers, it will usually be opened by default browser, such as txt, JPG, etc., will be displayed directly in the browser, if you need to prompt the user to save, we should use content-disposition to do a bit of processing, The key is to be sure to add attachment:


Field Description:
Content-disposition is a property name
How Disposition-type is downloaded, such as attachment for download by attachment
Disposition-parm is the file name when it is saved by default
When the server sends a file to the client browser, if it is a file type supported by the browsers, it will usually be opened by default browser, such as txt, JPG, etc., will be displayed directly in the browser, if you need to prompt the user to save, we should use content-disposition to do a bit of processing, The key is to be sure to add attachment:


Field Description:
Content-disposition is a property name
How Disposition-type is downloaded, such as attachment for download by attachment
Disposition-parm is the file name when it is saved by default
When the server sends a file to the client browser, if it is a file type supported by the browsers, it will usually be opened by default browser, such as txt, JPG, etc., will be displayed directly in the browser, if you need to prompt the user to save, we should use content-disposition to do a bit of processing, The key is to be sure to add attachment:

Note: This will prompt the browser to save or open, even if you choose to open, will also use the associated program such as Notepad open, instead of IE directly opened.

so the concrete examples are:

Content-disposition:attachment; Filename= "Filename.xls"
Of course, the filename parameter can contain path information, but user-agnet ignores the information and only makes the last part of the path information the file name. When you use this header message in response type Application/octet-stream, it means that you don't want to display the content directly, but instead pop up a "File download" dialog box, and then you decide whether to "open" or "save".

Java File download

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.