Java Web (XII) Commons fileUpload upload and download

I have a normal mind today... keep trying..

                      --WZY

1、 Upload principle and code analysis.

Upload: we send the resources to be uploaded to the server and save them on the server.

Download: when downloading a resource, the resource on the server is sent to the browser.

Difficulty: it is troublesome for the server to obtain resources,

Browser side

Note: enctype = multipart / form data: this attribute indicates that the content of the sent request body is multi form elements. Generally speaking, there are all kinds of data, including binary data, form data, etc., so use this attribute to distinguish them, The sending format is as follows (information captured by using the firebug plug-in in Firefox.)

Using multipart / form data, there will be a boundary attribute to separate the submitted form data, so as to let the server know which resources we upload and which ordinary form data.

Server side,

If we do not use the Commons fileUpload plug-in to help us process the uploaded data and let us handle it manually, it is also possible, but it is very troublesome, because we need to obtain all the request bodies, and then split them through the string and the boundary attribute, Then we get the data we want step by step.

Use commons file upload to process the uploaded content.

Code

Note that the stream operation is different from the file operation. What is the difference between mkdirs() and mkdir()? They are all used to create folders. The difference is that mkdirs can create multi-level directories, while MKDIR () can only create the current folder. If it is found that the upper level directory has not been created, it will be indifferent and do nothing, so it cannot create the current folder. You must create the upper level folder first.

There are still many problems to be solved, such as the garbled code of uploaded file names, the garbled code of single table contents, and the same name of uploaded files. If the uploaded files are large, how to deal with them, for example, how to deal with too many files in the same level directory. Each time I manually write the output stream and save the content to the specified location. It's too troublesome. Now I write an enhanced version to solve all the above problems.

Upload file name garbled problem: use servletfileupload setHeaderEncoding("UTF-8"); Or request SetCharacterEncoding ("UTF-8") is OK

Garbled form content: just use getString ("UTF-8"), that is, you can set the code table when you get the content.

Upload file with the same name: use UUID randomUUID(). toString(). replace("-",""). Get a unique 32-bit number

Use FileUtils copyInputStreamToFile(is,file); To output the contents to the specified path file, and mkdirs () automatically creates a directory

There are too many files in the same level directory: create a multi-level directory. Through the hashcode value of the file name, the hashcode is int type, accounting for 4 bytes, and one byte accounts for 8 bits, that is, 32 bits. Group them into groups of 4 bits and 4 bits, and they can be divided into 8 groups. Each time represents a layer of directory, it can be divided into 8 layers of directories. In each layer, There are 16 different folders that can be created. In this way, there can be many, many folders. Many files can be saved under each folder. Depending on our business requirements, we can decide how many layers of directories to create, so we can take several groups of data from hashcode. The schematic diagram is as follows

Generate two-level directory

Code

Upload code

If you need to make an upload progress bar, you can use the listener to monitor the progress of uploaded data and implement progresslistener.

Summary upload:

In fact, it's not very difficult to understand. It's just that the processing after uploading files is troublesome. For all kinds of small problems, the storage process is the most troublesome.

1. Create factory class

2. Use core classes,

3. Parse the request,

4. Traverse the content of the request body to obtain both the uploaded content and the content of the ordinary form

5. When the uploaded content is obtained, set its storage location

Many of the details have been made clear above, and there are many comments in the code.

2、 Download principle and code implementation

There are two ways to download,

First, use the a tag, that is, use the hyperlink. If the browser can parse it, it will be displayed directly. If it cannot parse it, it will be downloaded. This method is not very good,

I use Firefox. The first and third can be parsed directly, while the second can't be parsed. It shows the download page

The second way:

1. Set the response header to let the browser know that it should download rather than parse

            response. setHeader("content-disposition","attachment;filename=" +fileName); / / set the content disposition response header

2. Get the input stream and point to the file to be downloaded

            InputStream is = this. getServletContext(). getResourceAsStream("/download/1.jpg");

3. Obtain the output stream and transfer its file to the browser

            ServletOutputStream out = response. getOutputStream();

4. Use ioutils copy(is,out); Directly passing in the input stream and output stream will help us output the content read by the output stream to the browser through the output stream. The internal implementation principle should be as follows

                int b = -1;

                byte[] bf = new byte[1024];

                while((b=is.read(bf)) != - 1){

                  out. write(bf,b);

                }

Note: the download file name written here does not contain Chinese, so it can be displayed normally. If it is written in Chinese, it will be garbled, and even Chinese will not be displayed. There are two ways to deal with this Chinese garbled problem

1. Simple treatment

             fileName = new String(fileName.getBytes("gbk"),"ISO8859-1");

             fileName = new String(fileName.getBytes("utf-8"),"ISO8859-1");

             fileName = new String(fileName.getBytes(),"ISO8859-1"); / / this is the same as the first. The default code is GBK.

Principle

The above code means that the filename is encoded using GBK or UTF-8, and then decoded using iso8859-1. At this time, the filename is a garbled text. See the following two diagrams for the specific schematic diagram

This figure explains what the above code does. Let me briefly dictate the whole coding process. On the server side, write the above code. Beauty is in Chinese. After coding it with GBK code table, you will get a symbol recognized by the computer, such as 123, Then we decode the symbol 123 recognized by the computer into Chinese characters we know by using the iso8859-1 code table, but it cannot be displayed normally because the code table used for encoding and decoding is different, that is, the filename itself is a garbled text, and then in the response header, it is encoded by using the iso8859-1 code table, Therefore, the garbled text of filename itself will become 123 recognized by the machine. When it comes to the browser, because 123 is encoded by GBK, if GBK is used for decoding, it will be displayed correctly. This is the process

If you don't know what is encoding and what is decoding, take a look at the blog post on how to solve the garbled problem of request and response, which should solve your questions.

Code:

2. Complex treatment

Different operations are performed according to different browsers. Set according to different browsers. IE and Google URL coding, Firefox adopts Base64 coding

IE and Google

/ / * ie Google uses URL encoding, just use URL to encode filename. Internally, it is similar to the idea of encoding and decoding explained above. You can output filename to see what the result is or XXX Jpg, the description is the process of encoding and decoding filename.            if(userAgent.contains("MSIE") || userAgent. Contains ("Chrome") {/ / judge whether it is Google or Internet Explorer. Filename = urlencoder.encode (filename, "UTF-8");}

Firefox uses Base64 encoding

There are two problems,

One is base64encoder. This class can't find the package. Refer to the solution to this problem

                           http://blog.csdn.net/jbxiaozi/article/details/7351768

                           http://www.cnblogs.com/silentjesse/archive/2013/03/07/2948146.html

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>