SpringMVC implements Image Upload and springmvc Image Upload
SpringMVC provides us with our own method to implement file upload with a large amount of code and low efficiency when using word throttling.
SpringMVC provides the CommonMultipartResolver component to upload files:
- Maximum size of maxUploadSize file, measured in bytes
- Files smaller than maxInMemorySize are saved in memory.
- Default defaultEncoding Encoding
For example:
<! -- FileUpload Support -->
<Bean id = "multipartResolver" class = "org. springframework. web. multipart. commons. CommonsMultipartResolver">
<Property name = "defaultEncoding" value = "UTF-8"/>
<! -- Max size: 10 M -->
<Property name = "maxUploadSize" value = "10485760"/>
</Bean>
In the preceding configuration, the id must be multipartResolver to ensure the upload. Cannot be named at will
This means that the bean must have the same id to work properly.
In this case, we will start to configure the form. We must add enctype = "multipart/form-data ":
Then remember to introduce two jar packages:
- Commons-fileupload.jar
- Commens-io-1.4.jar
Then we start to write the java code:
1. First, convert the request to MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
2. You can use getFile to obtain the file:
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest. getFile ("file ");
This file must be consistent with the name of input in form.
3. Finally, move the file to the target address:
FileCopyUtil. Extract (file. getByte (), uploadFile );
The above is a single file upload. For multi-File Upload, you can use getFileMap () of MultipartHttpServletRequest to retrieve all files passed through the form.
Then upload files in sequence using the for loop traversal:
After completing the file upload, let's talk about how to download the file:
File downloading mainly uses byte streams. There are three main points:
1. Set the encoding format to: text/html; charset = UTF-8
2. Set the value of Content-disposition in the header to attachment; filename = File Name (this file name is the name of the file in the pop-up window on the client)
3. Set the Context-Length attribute in the header. The value is the file size.
The above is a small example.
This is the website's file upload and download, how the app uploads files and how to handle the background is better still under study, if there is any good way to leave a message, help the younger brother, hahaha.
In addition, the Android app also has enctype = "multipart/form-data", which is in the request header and is available based on the http protocol, then upload images on all webpages and apps.
Here is just a simple demo logic code that should not be written in the controller.
Note:
When using this MultipartFile, remember to add @ RequestParam to the front, or an error will be reported.
Http://www.cnblogs.com/liuling/p/2014-3-5.html #
If you encounter any problems, you will continue to update them.
Thank you for your support!