Java Web file download 1-File Download implementation and garbled Processing

Source: Internet
Author: User

Java Web file download 1-File Download implementation and garbled Processing

File upload and download are common problems in web development. In the past few days, I have used file downloads for a project. I have also separated some notes and made some preparations today. File Upload is pending for further testing. Here we will first talk about file download.

I. File Download Process

The file download process is clear:

1. Locate the file based on the file name or file path. The specific policy mainly depends on your needs. In short, you need the full file path that the system can find.

2. Get the input stream and get the input stream from the target file.

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

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

5. Close the IO stream.

This is the main process, and some necessary attribute settings, such as the contentType type of the setting file.

2. Don't worry. Go to the code

I use Springmvc, but the same is true for others. I mainly need HttpServletResponse objects and valid target files.

1. Front-end code

/** Download the uploaded file */function downloadFromUpload (fileName) {window. location. href = path + "/download? Dir = upload & fileName = "+ encodeURI (fileName);}/** normal download */function download (fileName) {window. location. href = path + "/download? Dir = download & fileName = "+ encodeURI (fileName ));}

2. controller code

/*** File download (download from the upload path) ** @ param request * @ param response * @ throws IOException */@ ResponseBody @ RequestMapping (value = "/download ") public void downloadFile (HttpServletRequest request, HttpServletResponse response, FileModel model) throws Exception {String fileName = URLDecoder. decode (model. getFileName (), "UTF-8");/** 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") + ", Username:" + (String) (request. getSession (). getAttribute ("username") + ", downloaded file:" + fileAbsolutePath );}
The download logic here is that the front-end only needs to request/download and provide the file name parameter. To avoid Chinese garbled characters, when the front-end file name is used as a parameter, the js encodeURI () is used to convert it to a Unicode code, and then the background decoding is converted to a Chinese character. In addition, due to the special nature of the project, the files to be downloaded here may be in the upload and download folders, so some judgment logic is added here. In addition, I encapsulate the file name and the requested folder name in FileModel.

3. Download logic implementation. The service is not used here, and the static method is directly used for implementation.

/*** Specify the download name ** @ param request * HttpServletRequest * @ param response * HttpServletResponse * @ param filePath * full file path * @ param fileName * specifies the client download time display file name * @ throws IOException */public static void downloadFile (HttpServletRequest request, httpServletResponse response, String filePath, String fileName) throws IOException {BufferedInputStream bis = null; BufferedOutputStream bos = null; bis = new Buff EredInputStream (new FileInputStream (filePath); bos = new BufferedOutputStream (response. getOutputStream (); long fileLength = new File (filePath ). length (); response. setCharacterEncoding ("UTF-8"); response. setContentType ("multipart/form-data");/** address Chinese garbled characters in various browsers */String userAgent = request. getHeader ("User-Agent"); byte [] bytes = userAgent. contains ("MSIE ")? FileName. getBytes (): fileName. getBytes ("UTF-8"); // fileName. getBytes ("UTF-8") handle safari garbled problem fileName = new String (bytes, "ISO-8859-1"); // Each browser basically supports ISO encoding 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 ();} /*** when downloading an object, the download object name is not specified ** @ param request * HttpServletRequest * @ param response * HttpServletResponse * @ param filePath * full file 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. getName ());}


Here we provide an overloaded Download Method to Solve the need to specify the file name to download from the client.

Iii. Notes

1. Selection of MIME types

I was not very familiar with the MIME type. I found that the MIME type settings of many source codes downloaded on the Internet are different. That is, this sentence

 response.setContentType("multipart/form-data");
After checking the settings, the role of setting the MIME type is to tell the client browser in what format to process the file to be downloaded. There are a lot of explanations on the corresponding network. This Class I is set to this format, and the format is generally automatically matched.

2. Specify the client download file name

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

 response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
Can be customized. Do not change the previous part.

3. troubleshooting of Chinese garbled characters

Chinese file garbled code is too common, when the project system architecture is just built, it should be unified all the Chinese encoding, including the editor, page and database, recommended UTF-8 encoding. If Spring is used, you can configure the Spring Character Set filter to avoid Chinese garbled characters.

(1) garbled file names during client download requests

Sometimes we encounter that the Chinese file name download list is normal on the front-end page, but we found that the file name in the request is garbled in the background, then we can solve the problem by using the above mentioned encodeURI.

(2) garbled file names during client download and execution

In actual tests, it is found that Chinese file names in ie may contain garbled characters when other browsers can execute. I saw such a piece of code on the Internet. After testing, it perfectly solved the problem of Chinese garbled characters in different browsers.

/** Solve Chinese garbled characters in various browsers */String userAgent = request. getHeader ("User-Agent"); byte [] bytes = userAgent. contains ("MSIE ")? FileName. getBytes (): fileName. getBytes ("UTF-8"); // fileName. getBytes ("UTF-8") handle safari garbled problem fileName = new String (bytes, "ISO-8859-1"); // Each browser basically supports ISO encoding response. setHeader ("Content-disposition", String. format ("attachment; filename = \" % s \ "", fileName ));


(3) garbled files on the server

Different servers may have different encoding methods for the platform, so pay attention to them here. For specific solutions, see the previous article: Garbled Chinese Characters During file download.

For original works, please indicate the source for reprinting.









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.