Upload a file instance in Spring MVC, springmvc

Source: Internet
Author: User

Upload a file instance in Spring MVC, springmvc

SpringMVC (annotation) Notes for file upload:
1. form's enctype = "multipart/form-data", which is required for uploading files
2. applicationContext. xml configuration:

Copy codeThe Code is as follows:
<! -- When uploading files, SpringMVC needs to configure the MultipartResolver Processor -->
<Bean id = "multipartResolver" class = "org. springframework. web. multipart. commons. CommonsMultipartResolver">
<Property name = "defaultEncoding" value = "UTF-8"/>
<! -- The total size of the uploaded file cannot exceed kb. Note that the limit of the maxUploadSize attribute is not for a single file, but for the total capacity of all files -->
<Property name = "maxUploadSize" value = "200000"/>
<! -- Maximum memory size (10240) -->
<Property name = "maxInMemorySize" value = "40960"/>
</Bean>

<! -- SpringMVC throws org. springframework. web. multipart. MaxUploadSizeExceededException when the file upload limit is exceeded. -->
<! -- This exception was thrown by SpringMVC when checking the information of the uploaded file, and has not yet 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>

Form pages/WEB-INF/jsp/upload. jsp for uploads
Copy codeThe Code is as follows:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8"
PageEncoding = "UTF-8" %>
<% @ Taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Script type = "text/javascript" src = ".../js/jquery-1.7.1.min.js"> </script>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> upload an image </title>
</Head>
<Body>
<Form action = "<% = request. getContextPath () %>/upload/filesUpload" method = "POST" enctype = "multipart/form-data">
Yourfile: <input type = "file" name = "myfiles"/> <br/>
Yourfile: <input type = "file" name = "myfiles"/> <br/>
<Input type = "submit" value = "Upload image"/>
</Form>
</Body>
</Html>

When the content of the uploaded file is too large, the prompt page/WEB-INF/jsp/error_fileupload.jsp

Copy codeThe Code is as follows:
<% @ Page language = "java" pageEncoding = "UTF-8" %>
<H1> the file is too large. Please reselect it

Core UploadController class for file uploading

Copy codeThe Code is as follows:
Package com. ljq. web. controller. annotation;
 
Import java. io. File;
 
Import javax. servlet. http. HttpServletRequest;
 
Import org. springframework. stereotype. Controller;
Import org. springframework. web. bind. annotation. RequestMapping;
Import org. springframework. web. bind. annotation. RequestParam;
Import org. springframework. web. multipart. MultipartFile;
 
/**
* Upload images
*
* @ Author Administrator
*
*/
@ Controller
@ RequestMapping ("/upload ")
Public class UploadController {
 
@ RequestMapping ("/toUpload ")
Public String toUpload (){
Return "/upload ";
}
 
/***
* Save the file
*
* @ Param file
* @ Return
*/
Private boolean saveFile (HttpServletRequest request, MultipartFile file ){
// Determine whether the file is empty
If (! File. isEmpty ()){
Try {
// Save the file path (if the Tomcat server is used, the file will be uploaded to the \ % atat_home % \ webapps \ YourWebProject \ upload \ folder)
String filePath = request. getSession (). getServletContext ()
. GetRealPath ("/") + "upload/" + file. getOriginalFilename ();
File saveDir = new File (filePath );
If (! SaveDir. getParentFile (). exists ())
SaveDir. getParentFile (). mkdirs ();

// Transfer an object
File. transferTo (saveDir );
Return true;
} Catch (Exception e ){
E. printStackTrace ();
}
}
Return false;
}
 
/**
* Upload images
*
* @ Param files
* @ Param request
* @ Return
*/
@ RequestMapping ("/filesUpload ")
Public String filesUpload (@ RequestParam ("myfiles") MultipartFile [] files,
HttpServletRequest request ){
If (files! = Null & files. length> 0 ){
For (int I = 0; I <files. length; I ++ ){
MultipartFile file = files [I];
// Save the file
SaveFile (request, file );
}
}

// Redirect
Return "redirect:/upload/toUpload ";
}
 
}

The upload and development of this file is complete.

Common MultipartFile methods:
String getContentType () // obtain the object MIME type
InputStream getInputStream () // returns 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

Related Article

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.