Spring MVC file upload

Overview
file upload Java Web project is common functions, did not succeed to upload files, you need the following steps:
1. The form of the method attribute must be set to POST.
2. Form enctype attribute must be set to multipart / form-data (browser only way to use a binary stream processed form data).
3.pom file, add commons-fileupload dependence.
4. MultipartResolver disposed in Spring MVC profile.
Example file upload
completed sample program still preceding paragraphs SpringMVCProject project (previously connected: https://www.jianshu.com/p/fde4557c527c ).
File upload page background image
to create the folder "images", put a background image in the webapp directory of the project, named "backImage.jpg":

backImage

POM configuration file
to add commons-fileupload rely on pom files of the project:

  1 <dependency>
  2     <groupId>commons-fileupload</groupId>
  3     <artifactId>commons-fileupload</artifactId>
  4     <version>1.4</version>
  5 </dependency>

Create a JSP file
created uploadfile.jsp file in webapp directory of the project, write the following program:
  1 <%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
  2 <html>
  3 <head>
  4     <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
  5     <title>uploadfile</title>
  6     <style type="text/css">
  7         body{
  8             background-image: url(images/backImage.jpg);
  9             background-size:cover;
 10         }
 11     </style>
 12 </head>
 13 <body>
 14 <center>
 15 <h3>文件上传页面</h3>
 16 <br>
 17 <form action="upload" method="post" enctype="multipart/form-data">
 18     <table>
 19         <tr>
 20             <td><label>文件信息:</label></td>
 21             <td><input type="text" name="information"></td>
 22         </tr>
             <TD> <label> Select File: </ label> </ td
24         <TR>
23 is 25             <td><input type="file" name="file"></td>
 26         </tr>
 27         <tr>
 28             <td><input type="submit" id="submit" value="上传"></td>
 29         </tr>
 30     </table>
 31 </form>
 32 </center>
 33 </body>
 34 </html>

Create a Controller class
to create UploadFileController class files in com.snow.dcl.controller package, write the following program:
  1 @Controller
  2 public class UploadFileController {
  3     @RequestMapping(value = "/upload", method = RequestMethod.POST)
  4     @ResponseBody
  5     public String upload(HttpServletRequest request, @RequestParam("information") String information, @RequestParam("file") MultipartFile file) throws IOException {
  6         if (!file.isEmpty()) {
  7             String path = request.getServletContext().getRealPath("file");
  8             String fileName = file.getOriginalFilename();
  9             File uploadFile = new File(path, fileName);
 10             if (!uploadFile.getParentFile().exists()) {
 11                 uploadFile.getParentFile().mkdirs();
 12             }
 13             file.transferTo(new File(path + File.separator + fileName));
 14             return "Success!";
 15         } else {
 16             return "No File!";
 17         }
 18     }
 19 }

Use the controller program in the @ResponseBody notes, you can return to the "File uploaded successfully!" And string data "is not added upload files!" To the front, otherwise the configuration of Spring MVC configuration file springmvc-servlet.xml in return view jsp files.
springmvc-servlet.xml configuration file
in the configuration file springmvc-servlet.xml MultipartResolver, increasing profile as follows:
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <beans xmlns="http://www.springframework.org/schema/beans"
  3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4       xmlns:context="http://www.springframework.org/schema/context"
  5       xmlns:mvc="http://www.springframework.org/schema/mvc"
  6       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http: // www .springframework.org / Schema / context / Spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">
   . 7  
  . 8      <-! spring in the java class can automatically scan base-package set of sub-packets, or packets, if the class has to scan the relevant annotated spring, the spring is registered as the bean ->
   . 9      <context: scan-Component base- Package = " com.snow.dcl.controller " />
 10  
. 11      <MVC: Annotation-Driven />
 12 is      <MVC: default -servlet-Handler />
 13 is  
14      <!
- view resolver -> 15     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 16         <property name="prefix">
 17             <value>/WEB-INF/content/</value>
 18         </property>
 19         <property name="suffix">
 20             <value>.jsp</value>
 21         </property>
 22     </bean>
 23 
 24     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver ">
 25          <-! upload file size less than 20M ->
 26 is          <Property name =" maxUploadSize ">
 27              <value> 20971520 </ value>
 28          </ Property>
 29          <! - requested coding format, must be the same attribute value pageEncoding JSP file ->
 30          <property name = " defaultEncoding ">
 31 is              <value>. 8 UTF-</ value>
 32          </ property>
 33 is      </ the bean>
 34 is  
35 </ Beans>
 36 


Note:
1. configure MultipartResolver also added the mvc namespace.
2. Add <mvc: default-servlet-handler /> configured to process images and other background static resource.
3. Add <mvc: default-servlet-handler /> configuration you must add <mvc: annotation-driven /> otherwise the situation will not be resolved @Controller notes, leading to process the request type request when they are not matched, we all go <mvc: default-servlet-handler /> i.e. the default servlet process, static resources (e.g., image resource) because there is no corresponding Controller default servlet will be processed.
Test
start TomcatServer, after startup is complete, open your browser and enter: HTTP: // localhost: 8080 / uploadfile.jsp , a successful visit. Do not add any file, direct submission: add a test with a txt file: Submit: View project directory under the project directory target directory will generate a file directory, upload files in the file directory: At this point, file upload function recording is completed.
Spring MVC upload 01

Spring MVC upload 03

Spring MVC upload 02

Spring MVC upload 04

Spring MVC upload 05

Guess you like

Origin www.cnblogs.com/Dcl-Snow/p/11606559.html