Example of Spring MVC file upload in java

Source: Internet
Author: User
Tags exception handling file size file upload

First, you need to add two jar packages:
Commons-fileupload-1.2.2.jar
Commons-io-2.1.jar

1. File configuration

SpringMVC uses MultipartFile for file upload. Therefore, we must first configure MultipartResolver to explicitly tell DispatcherServlet how to handle MultipartRequest.

<Bean id = "multipartResolver" class = "org. springframework. web. multipart. commons. CommonsMultipartResolver">
<Property name = "defaultEncoding" value = "utf-8"> </property>
<Property name = "maxUploadSize" value = "10485760000"> </property>
<Property name = "maxInMemorySize" value = "40960"> </property>
</Bean>
Details about attributes:

DefaultEncoding = "UTF-8 & Prime; is the request encoding format, which defaults to the ISO-8859-1
MaxUploadSize = "5400000 & Prime; indicates the size of the uploaded file, in bytes.
UploadTempDir = "fileUpload/temp" is the temporary PATH for uploading files.

Note that the file size here is actually only the total size of all files. If the file size is not set, the file size is not limited by default.
If the file size is configured, you need to configure exception control.
Therefore, you need to configure abnormal display.

<! -When SpringMVC exceeds the file upload limit, it will throw org. springframework. web. multipart. MaxUploadSizeExceededException->
<! -This exception was thrown by SpringMVC when checking the uploaded file information. At this time, SpringMVC has not entered the Controller method.->

<Bean id = "exceptionResolver"
Class = "org. springframework. web. servlet. handler. SimpleMappingExceptionResolver">
<Property name = "exceptionMappings">
<Props>
<! -- Encounter MaxUploadSizeExceededException exception, automatically jump to/WEB-INF/jsp/error_fileupload.jsp page -->
<Prop
Key = "org. springframework. web. multipart. MaxUploadSizeExceededException"> error_fileupload </prop>
</Props>
</Property>
</Bean>
If you want to control the returned information, you can consider returning data in the specified format in exception handling, such as JSON ??

After the configuration is complete, add "enctype =" multipart/form-data ", method =" post "to the form"
Then there is the action to be processed. There are two ways to do this:

Method 1:

Single file

Public String xxx (@ RequestParam MultipartFile file ,...){
..................
}
Multiple files

Public String xxx (@ RequestParam MultipartFile [] files ,...){
..................
}
Method 2:

Public ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws Exception {
// Transform to MultipartHttpRequest:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// Obtain the file:
MultipartFile file = multipartRequest. getFile ("file ");
}
Sample code

@ RequestMapping ("/upload2 ")
Public String upload2 (HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
// Create a common multi-part parser
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver (request. getSession (). getServletContext ());
// Determine whether the request has a file upload, that is, multiple requests
If (multipartResolver. isMultipart (request )){
// Convert the request to multiple parts
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// Retrieve all file names in the request
Iterator <String> iter = multiRequest. getFileNames ();
While (iter. hasNext ()){
// Obtain the uploaded file
MultipartFile file = multiRequest. getFile (iter. next ());
If (file! = Null ){
// Obtain the name of the file to be uploaded
String myFileName = file. getOriginalFilename ();
// If the name is not "", the file exists; otherwise, the file does not exist.
If (myFileName. trim ()! = ""){
// Define the upload path
String path = request. getSession (). getServletContext (). getRealPath ("/upload") + file. getOriginalFilename ();
File localFile = new File (path );

// Efficiency is much higher than byte transfer
File. transferTo (localFile );
                }
            }
        }    
    }
Return "/success ";
}
Common MultipartFile methods:
String getContentType () // Obtain the object MIME type
InputStream getInputStream () // then go to the File Stream
String getName () // Get the name of the file component in the form
String getOriginalFilename () // obtain the original name of the uploaded file
Long getSize () // obtains the object's byte size. The unit is byte.
Boolean isEmpty () // whether it is null
Void transferTo (File dest) // save it to a target File

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.