Spring MVC4使用Servlet3 MultiPartConfigElement文件上传实例
2021-07-20 06:05
YPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
å¨è¿ç¯æç« ä¸ï¼æ们å°ä½¿ç¨Servlet3.0以åjavax.servlet.MultipartConfigElementï¼ä¸ºäºæ¿æ´»Â Servlet3.0ç¯å¢åSpring çMultipartæ¯æï¼ä½ éè¦å以ä¸ï¼
1.æ·»å StandardServletMultipartResolver Bean å¨ Spring é ç½®ãè¿æ¯ä¸ä¸ªæ åå®ç° MultipartResolver æ¥å£ï¼åºäºServlet3.0 javax.servlet.http.Part APIã
2. å¯ç¨å¨Servlet3.0ç¯å¢çå¤è§£æ(MultiParsing)ãè¦åå°è¿ä¸ç¹ï¼ä½ æå¤ç§æ¹æ¡å¯ä¾éæ©ã
- æ¹æ¡A. 对æ¹æ¡æ§ Servlet 注å设置 javax.servlet.MultipartConfigElementãMultipartConfigElementæ¯javax.servlet.annotation.MultipartConfig ç注éå¼(å¦éæ©Cæè¿°)çç®åJava类表示ã è¿ç¯æç« å°ç¹å«ä¾§éäºè¿ä¸ªéæ©ã
- æ¹æ¡B. å¦ææ¨ä½¿ç¨åºäºXMLçé
ç½®ï¼å¯ä»¥å¨web.xmlä¸å¨servleté
置声æ multipart-configsection é¨åï¼å¦ä¸å¾æ示ï¼
SpringDispatcher org.springframework.web.servlet.DispatcherServlet /tmp 5242880 20971520 0 - æ¹æ¡C. å¯ä»¥å建ä¸ä¸ªèªå®ä¹ Servlet å javax.servlet.annotation.MultipartConfig æ 注å
¶æ 注ï¼å¦ä¸å¾æ示ï¼
@WebServlet(name = "fileUploadServlet", urlPatterns = {"/upload"}) @MultipartConfig(location=/tmp, fileSizeThreshold=0, maxFileSize=5242880, // 5 MB maxRequestSize=20971520) // 20 MB public class FileUploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //handle file upload }
- Spring 4.2.0.RELEASE
- validation-api 1.1.0.Final
- Bootstrap v3.3.2
- Maven 3
- JDK 1.7
- Tomcat 8.0.21
- Eclipse JUNO Service Release 2
Letâs begin.
4.0.0 com.yiibai.springmvc Spring4MVCFileUploadMultipartFilewar 1.0.0 Spring4MVCFileUploadMultipartFile Maven Webapp http://maven.apache.org 4.2.0.RELEASE org.springframework spring-webmvc${springframework.version} javax.validation validation-api1.1.0.Final javax.servlet javax.servlet-api3.1.0 javax.servlet jstl1.2 org.apache.maven.plugins maven-war-plugin2.4 src/main/webapp Spring4MVCFileUploadMultipartFile false Spring4MVCFileUploadMultipartFile
package com.yiibai.springmvc.configuration; import javax.servlet.MultipartConfigElement; import javax.servlet.ServletRegistration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class>[] getRootConfigClasses() { return new Class[] { HelloWorldConfiguration.class }; } @Override protected Class>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setMultipartConfig(getMultipartConfigElement()); } private MultipartConfigElement getMultipartConfigElement() { MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD); return multipartConfigElement; } private static final String LOCATION = "C:/temp/"; // Temporary location where files will be stored private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size. // Beyond that size spring will throw exception. private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part. private static final int FILE_SIZE_THRESHOLD = 0; // Size threshold after which files will be written to disk }
é ç½®StandardServletMultipartResolver Beanãè¿æ¯ä¸ä¸ªæ åå®ç°MultipartResolveræ¥å£ï¼åºäºServlet3.0 javax.servlet.http.Part APIã
package com.yiibai.springmvc.configuration; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.web.multipart.support.StandardServletMultipartResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.yiibai.springmvc") public class HelloWorldConfiguration extends WebMvcConfigurerAdapter { @Bean(name = "multipartResolver") public StandardServletMultipartResolver resolver() { return new StandardServletMultipartResolver(); } @Override public void configureViewResolvers(ViewResolverRegistry registry) { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); registry.viewResolver(viewResolver); } @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations( "/static/"); } }
messages /WEB-INF/views/ .jsp
Springæä¾ org.springframework.web.multipart.MultipartFileï¼ è¿æ¯ä¸ä¸ª multipart 请æ±è·å¾ä¸ä¼ æ件ç表示ã å®æä¾äºæ¹ä¾¿çæ¹æ³ï¼å¦getName()ï¼getContentType()ï¼GetBytes()ï¼getInputStream()çãè¿è®©æ们å¤çæ´å®¹æä¸ç¹ï¼åæ¶æ£ç´¢æå ³è¢«ä¸ä¼ æ件çä¿¡æ¯ã
package com.yiibai.springmvc.model; import org.springframework.web.multipart.MultipartFile; public class FileBucket { MultipartFile file; public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } }
package com.yiibai.springmvc.model; import java.util.ArrayList; import java.util.List; public class MultiFileBucket { Listfiles = new ArrayList (); public MultiFileBucket(){ files.add(new FileBucket()); files.add(new FileBucket()); files.add(new FileBucket()); } public List getFiles() { return files; } public void setFiles(List files) { this.files = files; } }
package com.yiibai.springmvc.controller; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.FileCopyUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import com.yiibai.springmvc.model.FileBucket; import com.yiibai.springmvc.model.MultiFileBucket; import com.yiibai.springmvc.util.FileValidator; import com.yiibai.springmvc.util.MultiFileValidator; @Controller public class FileUploadController { private static String UPLOAD_LOCATION="C:/mytemp/"; @Autowired FileValidator fileValidator; @Autowired MultiFileValidator multiFileValidator; @InitBinder("fileBucket") protected void initBinderFileBucket(WebDataBinder binder) { binder.setValidator(fileValidator); } @InitBinder("multiFileBucket") protected void initBinderMultiFileBucket(WebDataBinder binder) { binder.setValidator(multiFileValidator); } @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET) public String getHomePage(ModelMap model) { return "welcome"; } @RequestMapping(value = "/singleUpload", method = RequestMethod.GET) public String getSingleUploadPage(ModelMap model) { FileBucket fileModel = new FileBucket(); model.addAttribute("fileBucket", fileModel); return "singleFileUploader"; } @RequestMapping(value = "/singleUpload", method = RequestMethod.POST) public String singleFileUpload(@Valid FileBucket fileBucket, BindingResult result, ModelMap model) throws IOException { if (result.hasErrors()) { System.out.println("validation errors"); return "singleFileUploader"; } else { System.out.println("Fetching file"); MultipartFile multipartFile = fileBucket.getFile(); // Now do something with file... FileCopyUtils.copy(fileBucket.getFile().getBytes(), new File( UPLOAD_LOCATION + fileBucket.getFile().getOriginalFilename())); String fileName = multipartFile.getOriginalFilename(); model.addAttribute("fileName", fileName); return "success"; } } @RequestMapping(value = "/multiUpload", method = RequestMethod.GET) public String getMultiUploadPage(ModelMap model) { MultiFileBucket filesModel = new MultiFileBucket(); model.addAttribute("multiFileBucket", filesModel); return "multiFileUploader"; } @RequestMapping(value = "/multiUpload", method = RequestMethod.POST) public String multiFileUpload(@Valid MultiFileBucket multiFileBucket, BindingResult result, ModelMap model) throws IOException { if (result.hasErrors()) { System.out.println("validation errors in multi upload"); return "multiFileUploader"; } else { System.out.println("Fetching files"); ListfileNames = new ArrayList (); // Now do something with file... for (FileBucket bucket : multiFileBucket.getFiles()) { FileCopyUtils.copy(bucket.getFile().getBytes(), new File(UPLOAD_LOCATION + bucket.getFile().getOriginalFilename())); fileNames.add(bucket.getFile().getOriginalFilename()); } model.addAttribute("fileNames", fileNames); return "multiSuccess"; } } } Â
以ä¸æ§å¶å¨æ¯ç¸å½å¾®ä¸è¶³éãå®å¤çä¸ä¼ è§å¾çGETåPOST请æ±çæ件ãå½æ件ä»æ件éæ©å¨ï¼ç¨æ·éæ©ç¹å»ä¸ä¼ ï¼æ们åªæ¯åå»ºå ·æç¸åçå称ååèçå 容ä½ä¸ºåå§æ件çæ°æ件ï¼ä»åå§å¤å¶æ件çåèæ°ã为æ¤ï¼æ们æ£å¨ä½¿ç¨Spring FileCopyUtilså·¥å ·ç±»æµä»æºå¤å¶å°ç®çå°ãå¨è¿ä¸ªä¾åä¸ï¼æ们æå®çç®çå°æ¯Â C:/mytemp æ件夹ï¼æææ件å°åå¨è¿ä¸ªæ件夹ä¸ã
package com.yiibai.springmvc.util; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.yiibai.springmvc.model.FileBucket; @Component public class FileValidator implements Validator { public boolean supports(Class> clazz) { return FileBucket.class.isAssignableFrom(clazz); } public void validate(Object obj, Errors errors) { FileBucket file = (FileBucket) obj; if(file.getFile()!=null){ if (file.getFile().getSize() == 0) { errors.rejectValue("file", "missing.file"); } } } }
package com.yiibai.springmvc.util; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.yiibai.springmvc.model.FileBucket; import com.yiibai.springmvc.model.MultiFileBucket; @Component public class MultiFileValidator implements Validator { public boolean supports(Class> clazz) { return MultiFileBucket.class.isAssignableFrom(clazz); } public void validate(Object obj, Errors errors) { MultiFileBucket multiBucket = (MultiFileBucket) obj; int index=0; for(FileBucket file : multiBucket.getFiles()){ if(file.getFile()!=null){ if (file.getFile().getSize() == 0) { errors.rejectValue("files["+index+"].file", "missing.file"); } } index++; } } }
messages.properties
missing.file= Please select a file.
singleFileUploader.jsp
Spring 4 MVC File Upload Example Spring 4 MVC File Upload Example
Home
success.jsp
File Upload Success
multiFileUploader.jsp
Spring 4 MVC File Multi Upload Example
multiSuccess.jsp
File Upload Success
welcome.jsp
Spring 4 MVC File Upload Example Welcome to FileUploader Example
Click on below links to see FileUpload in action.
Single File Upload OR Multi File Upload
ç°å¨æ建 war(åé¢çEclipseæç¨)æéè¿Mavençå½ä»¤è¡( mvn clean install).é¨ç½²Â war å°Servlet3.0容å¨ã
æå¼æµè§å¨ï¼æµè§Â http://localhost:8080/Spring4MVCFileUploadMultipart/
æ¨å¯ä»¥æ¥çä¸ä¼ çæ件夹 [C:/mytemp] 对äºä¸ä¼ çæ件ãÂ
éæ©è¦ä¸ä¼ çæ件ã
æåï¼æ¥çåå¨æ件夹 [C:/mytemp].
下一篇:Spring MVC文件上传教程
文章标题:Spring MVC4使用Servlet3 MultiPartConfigElement文件上传实例
文章链接:http://soscw.com/index.php/essay/106492.html