Java Web Implementation file download and garbled processing method _java

Source: Internet
Author: User
Tags file upload java web

File upload and download is a common problem in web development, these days in doing a project and use the file to download, before also a little bit of fragmented notes, today to do a collation. File upload has yet to be further tested, here first to mention the file download.

File Download processing process

The file download processing process is actually very clear, namely:

1, according to the file name or file path location files, the specific strategy based on their own needs, in short, the system can find the file full path.

2. Get input stream, get input stream from target file.

3. Get the output stream and get the output stream from the response.

4. Read the file from the input stream and output the file through the output stream. This is the true download execution process.

5, close IO stream.

The main process is this, in addition to some of the necessary property settings, such as the more important to set the file contenttype type.

Second, not verbose, on the code

I do it with SPRINGMVC, but its practical other is the same, the main needs of HttpServletResponse objects and valid target files.

1. Front Code


* * Download uploaded file *
/function Downloadfromupload (fileName) {
window.location.href = path + "/download?dir= Upload&filename= "+encodeuri (encodeURI (FileName));
}
* * General download
/function Download (fileName) {
window.location.href = path + "/download?dir=download &filename= "+encodeuri (encodeURI (FileName));
}

2, Controller code

/** * File download (download from upload path) * * @param request * @param response * @throws IOException * * @Resp Onsebody @RequestMapping (value = "/download") public void DownloadFile (HttpServletRequest request, HttpServletResponse Response, Filemodel model) throws Exception {String fileName = Urldecoder.decode (Model.getfilename (), "UTF-8"); * * Limit only
Files in the upload and download folders can be downloaded/String folderName = "Download"; if (!
Stringutils.isempty (Model.getdir ()) && Model.getdir (). Equals ("Upload")) {folderName = "upload";} else {
FolderName = "Download"; String Fileabsolutepath = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "/web-inf/" + folderName + "/" +
FileName;
Filetools.downloadfile (Request, response, Fileabsolutepath); Log.warn ("User id:" + (Integer) (Request.getsession (). getattribute ("UserId")) + ", User name:" + (String) (Request.getsession (). GetAttribute ("username")) + ", download file:" + Fileabsolutepath);} 

The download logic here is that the front desk only needs to request/download and give the filename parameters. In order to avoid Chinese garbled, the file name of the foreground is used as the parameter, use JS's encodeURI () to turn it into Unicode code, and then the background decoding is converted to Chinese. In addition, due to the specificity of the project, I will download the file here may be in the upload and download two folders, so there is a part of the logic of judgment. Also, I encapsulate the filename and the requested folder name in the Filemodel.

3, download logic implementation.

There is no use of service, the direct use of static methods to achieve.

/** * Download the file specified download name * * @param request * HttpServletRequest * @param response * HttpServletResponse * @param filePath * File full 
PATH * @param filename * Specifies the filename to display when the client downloads * @throws IOException/public static void DownloadFile (HttpServletRequest request,
HttpServletResponse response, String FilePath, String fileName) throws IOException {Bufferedinputstream bis = null;
Bufferedoutputstream BOS = NULL;
bis = new Bufferedinputstream (new FileInputStream (FilePath));
BOS = new Bufferedoutputstream (Response.getoutputstream ());
Long filelength = new File (filePath). Length ();
Response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("Multipart/form-data");
* * Solve the Chinese garbled problem of the browser/String useragent = Request.getheader ("user-agent"); byte[] bytes = Useragent.contains ("MSIE")? Filename.getbytes (): Filename.getbytes ("UTF-8"); Filename.getbytes ("UTF-8") deals with the garbled problem of safari fileName = new String (bytes, "iso-8859-1"); Each browser basic support ISO coding Response.setheader ("Content-disposition", String.Format ("attachment; FilenaMe=\ "%s\" ", FileName)";
Response.setheader ("Content-length", String.valueof (Filelength));
byte[] buff = new byte[2048];
int bytesread;
while ( -1!= (bytesread = bis.read (buff, 0, buff.length))) {bos.write (buff, 0, bytesread);} bis.close ();
Bos.close ();
/** * Download files without specifying the download file name * * @param request * HttpServletRequest * @param response * HttpServletResponse * @param filePath  * File Full path * @throws IOException */public static void DownloadFile (HttpServletRequest request, httpservletresponse response, String FilePath) throws IOException {File File = new file (FilePath); DownloadFile (request, Response, FilePath, FILE.GETN
Ame ()); }

This provides an overloaded download method that addresses the need to specify the file name that the client downloads sometimes.

III. Matters of note

1, about the choice of MIME type

Before the MIME type is not very understanding, found that the internet has a lot of downloaded source code MIME type settings are not the same. That is the sentence

Response.setcontenttype ("Multipart/form-data");

Check this out. One of the roles of mime types is to tell the client browser what format to use to download files. The specific corresponding network has a lot of explanations, this type I set into this format, generally will automatically match the format.

2, specify the client download file name

Sometimes we may need to specify the file name when the client downloads the file, that is, the code

Response.setheader ("Content-disposition", String.Format ("attachment; Filename=\ "%s\" ", FileName)";
You can customize the filename in. The front part generally does not move.

3, the Chinese garbled problem solution

The Chinese file garbled is too common, in the project system structure just constructs, should unify all Chinese code, including in the editor, the page as well as the database, recommends the UTF-8 code. If you use spring, you can also configure spring's character set filter to further avoid Chinese garbled characters.

(1) Client download request process filename garbled

Sometimes we will encounter, the front page display Chinese file name download list Normal, but we went to the background to find the file name in the request garbled, then use the encodeURI mentioned above can be solved.

(2) When the client downloads execution, the filename is garbled

In the actual test found that in other browsers can be executed, ie under the Chinese file name may appear garbled. On the internet to see such a piece of code, after testing, the perfect solution to the different browsers of Chinese garbled problem


* * Solve the Chinese garbled problem of the
browser
/String useragent = Request.getheader ("user-agent");
byte[] bytes = Useragent.contains ("MSIE")? Filename.getbytes ()
: Filename.getbytes ("UTF-8");//Filename.getbytes ("UTF-8") deal with the garbled problem in Safari
fileName = new String (Bytes, "iso-8859-1"); Each browser basic support ISO coding
response.setheader ("Content-disposition",
String.Format ("attachment; Filename=\ "%s\" ", FileName)";

(3) file garbled on the server

Different servers may vary depending on the way the platform is encoded, and you need to be aware of this. Specific solutions see an article previously written: Chinese garbled processing during file downloading

The above is a small series to introduce the Java Web implementation file download and garbled processing methods, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.