鍍金池/ 教程/ Java/ Spring MVC文件上傳處理
Spring MVC表單處理
Spring MVC多項(xiàng)單選按鈕
Spring MVC Bean名稱Url處理程序映射
Spring MVC下拉選項(xiàng)(Select)
Spring MVC多動(dòng)作控制器
Spring4 MVC RESTFul Web Services CRUD實(shí)例+RestTemplate
Spring MVC頁(yè)面重定向
Spring MVC資源綁定視圖解析器
Spring4 MVC+Hibernate4 Many-to-many連接表+MySQL+Maven實(shí)例
Spring4 MVC REST服務(wù)示例使用@RestController
Spring MVC文本域
Spring4 MVC + AngularJS使用$http異步服務(wù)交互
Spring4 MVC文件下載實(shí)例
Spring4 MVC表單驗(yàn)證
Spring4 MVC RESTFul WebServices CRUD實(shí)例+RestTemplate
Spring MVC教程
Spring MVC參數(shù)方法名稱解析器
Spring MVC生成JSON數(shù)據(jù)
Spring MVC生成XML
Spring4 MVC 表單驗(yàn)證和資源處理 (使用注解)
Spring MVC單選按鈕
Spring MVC Xml視圖解析器
Spring MVC復(fù)選框
Spring4 MVC ContentNegotiatingViewResolver多種輸出格式實(shí)例
Spring MVC錯(cuò)誤處理
Spring MVC復(fù)選框(多項(xiàng))
Spring MVC Hibernate驗(yàn)證器
Spring4 MVC Hello World注解 (Java Config)實(shí)例
Spring MVC靜態(tài)頁(yè)面
Spring4 MVC ContentNegotiatingViewResolver實(shí)例
Spring MVC列表多選框
Spring MVC生成Excel格式數(shù)據(jù)
Spring MVC文本框
Spring MVC內(nèi)部資源視圖解析器
Spring4 MVC HelloWorld 注解和JavaConfig實(shí)例
Spring4 MVC REST服務(wù)使用@RestController實(shí)例
Spring MVC簡(jiǎn)單URL處理程序映射
Spring MVC4使用Servlet3 MultiPartConfigElement文件上傳實(shí)例
Spring MVC概述
Spring4 MVC使用Servlet 3 MultiPartConfigElement文件上傳實(shí)例
Spring4 MVC Hello WorldXML實(shí)例
Spring MVC屬性方法名稱解析器
Spring4 MVC + Hibernate4 + MySQL + Maven使用注解集成實(shí)例
Spring4 MVC + Hibernate4多對(duì)多連接表+MySQL+Maven實(shí)例
Spring4 MVC+Hibernate4+MySQL+Maven使用注解集成實(shí)例
Spring MVC配置靜態(tài)資源和資源包教程
Spring MVC可參數(shù)化的視圖控制器
Spring MVC生成RSS源
Spring4 MVC文件下載實(shí)例
Spring MVC密碼處理
Spring MVC隱藏字段域
Spring MVC文件上傳教程
Spring MVC多解析器映射
Spring MVC文件上傳處理
Spring4 MVC HelloWord實(shí)例
Spring MVC集成Log4j
Spring4 MVC+ AngularJS CRUD使用$http實(shí)例
Spring MVC - Hello World示例

Spring MVC文件上傳處理

以下示例顯示如何在使用Spring Web MVC框架的表單中上傳文件和處理。首先使用Eclipse IDE來創(chuàng)建一個(gè)WEB工程,實(shí)現(xiàn)一個(gè)上傳文件并保存的功能。并按照以下步驟使用Spring Web Framework開發(fā)基于動(dòng)態(tài)表單的Web應(yīng)用程序:

  1. 創(chuàng)建一個(gè)名稱為 FileUpload 的動(dòng)態(tài)WEB項(xiàng)目。
  2. com.yiibai.springmvc 包下創(chuàng)建兩個(gè)Java類FileModel, FileUploadController。
  3. jsp子文件夾下創(chuàng)建兩個(gè)視圖文件:fileUpload.jspsuccess.jsp
  4. WebContent文件夾下創(chuàng)建一個(gè)文件夾:temp。
  5. 下載Apache Commons FileUpload庫(kù):commons-fileupload.jarApache Commons IO庫(kù):commons-io.jar。把它們放在CLASSPATH中。
  6. 最后一步是創(chuàng)建所有源和配置文件的內(nèi)容并運(yùn)行應(yīng)用程序,詳細(xì)如下所述。

完整的項(xiàng)目文件目錄結(jié)構(gòu)如下所示 -

FileModel.java 的代碼如下所示 -

package com.yiibai.springmvc;

import org.springframework.web.multipart.MultipartFile;

public class FileModel {
   private MultipartFile file;

   public MultipartFile getFile() {
      return file;
   }

   public void setFile(MultipartFile file) {
      this.file = file;
   }
}

FileUploadController.java 的代碼如下所示 -

package com.yiibai.springmvc;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;


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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

   @Autowired
   ServletContext context; 

   @RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
   public ModelAndView fileUploadPage() {
      FileModel file = new FileModel();
      ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
      return modelAndView;
   }

   @RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
   public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
      if (result.hasErrors()) {
         System.out.println("validation errors");
         return "fileUploadPage";
      } else {            
         System.out.println("Fetching file");
         MultipartFile multipartFile = file.getFile();
         String uploadPath = context.getRealPath("") + File.separator + "temp" + File.separator;
         //Now do something with file...
         FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
         String fileName = multipartFile.getOriginalFilename();
         model.addAttribute("fileName", fileName);
         return "success";
      }
   }
}

FileUpload-servlet.xml 的代碼如下所示 -

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.yiibai.springmvc" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>

這里的第一個(gè)服務(wù)方法fileUploadPage(),我們已經(jīng)在名為“command”的ModelAndView對(duì)象中傳遞了一個(gè)空的FileModel對(duì)象,因?yàn)槿绻鸍SP文件中使用<form:form>標(biāo)簽,spring框架期望一個(gè)名稱為“command”的對(duì)象。 因此,當(dāng)調(diào)用fileUploadPage()方法時(shí),它返回fileUpload.jsp視圖。
第二個(gè)服務(wù)方法fileUpload()將根據(jù) URL => FileUpload/fileUploadPage上的POST方法進(jìn)行調(diào)用。將根據(jù)提交的信息準(zhǔn)備要上傳的文件。最后從服務(wù)方法返回“success”視圖,這將呈現(xiàn)success.jsp視圖。

fileUpload.jsp 的代碼如下所示 -

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Spring MVC上傳文件示例</title>
</head>
<body>
    <form:form method="POST" modelAttribute="fileUpload"
        enctype="multipart/form-data">
      請(qǐng)選擇一個(gè)文件上傳 : 
      <input type="file" name="file" />
        <input type="submit" value="提交上傳" />
    </form:form>
</body>
</html>

這里使用帶有value =“fileUpload”modelAttribute屬性來映射文件用服務(wù)器模型上傳控件。

success.jsp 的代碼如下所示 -

<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>Spring MVC上傳文件示例</title>
</head>
<body>
    文件名稱 :
    <b> ${fileName} </b> - 上傳成功!
</body>
</html>

完成創(chuàng)建源和配置文件后,發(fā)布應(yīng)用程序到Tomcat服務(wù)器。

現(xiàn)在啟動(dòng)Tomcat服務(wù)器,現(xiàn)在嘗試訪問URL => http://localhost:8080/FileUpload/fileUploadPage ,如果Spring Web應(yīng)用程序沒有問題,應(yīng)該看到以下結(jié)果:

提交所需信息后,點(diǎn)擊提交按鈕提交表單。 如果 Spring Web 應(yīng)用程序沒有問題,應(yīng)該看到以下結(jié)果: