Spring MVC - 檔案上傳示例



以下示例展示瞭如何在使用 Spring Web MVC 框架的表單中使用檔案上傳控制元件。首先,讓我們準備好一個可用的 Eclipse IDE,並按照以下步驟使用 Spring Web 框架開發一個基於動態表單的 Web 應用程式。

步驟 描述
1 建立一個名為 HelloWeb 的專案,位於 com.tutorialspoint 包下,如 Spring MVC - Hello World 章節中所述。
2 在 com.tutorialspoint 包下建立 Java 類 FileModel 和 FileUploadController。
3 在 jsp 子資料夾下建立檢視檔案 fileUpload.jsp 和 success.jsp。
4 在 WebContent 子資料夾下建立一個名為 temp 的資料夾。
5 下載 Apache Commons FileUpload 庫 commons-fileupload.jar 和 Apache Commons IO 庫 commons-io.jar。將它們放到你的 CLASSPATH 中。
6 最後一步是建立原始檔和配置檔案的內容,並匯出應用程式,如下所述。

FileModel.java

package com.tutorialspoint;

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.tutorialspoint;

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";
      }
   }
}

HelloWeb-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.tutorialspoint" />

   <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>

在這裡,對於第一個服務方法 fileUploadPage(),我們在 ModelAndView 物件中傳遞了一個空的 FileModel 物件,名稱為 "command",因為如果在 JSP 檔案中使用 <form:form> 標籤,Spring 框架會期望一個名為 "command" 的物件。因此,當呼叫 fileUploadPage() 方法時,它會返回 fileUpload.jsp 檢視。

第二個服務方法 fileUpload() 將針對 HelloWeb/fileUploadPage URL 上的 POST 方法呼叫。您將根據提交的資訊準備要上傳的檔案。最後,服務方法將返回 "success" 檢視,這將導致渲染 success.jsp。

fileUpload.jsp

<%@ page contentType="text/html; charset = UTF-8" %>
<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<html>
   <head>
      <title>File Upload Example</title>
   </head>
   
   <body>
      <form:form method = "POST" modelAttribute = "fileUpload"
         enctype = "multipart/form-data">
         Please select a file to upload : 
         <input type = "file" name = "file" />
         <input type = "submit" value = "upload" />
      </form:form>
   </body>
</html>

在這裡,我們使用 modelAttribute 屬性,其值為 "fileUpload",將檔案上傳控制元件與伺服器模型對映。

success.jsp

<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
   <head>
      <title>File Upload Example</title>
   </head>
   <body>
      FileName : 
      lt;b> ${fileName} </b> - Uploaded Successfully.
   </body>
</html>

建立完原始檔和配置檔案後,匯出應用程式。右鍵單擊應用程式,使用 匯出 → WAR 檔案 選項並將 HelloWeb.war 檔案儲存到 Tomcat 的 webapps 資料夾中。

現在,啟動 Tomcat 伺服器,並確保您可以使用標準瀏覽器從 webapps 資料夾訪問其他網頁。嘗試 URL – https://:8080/HelloWeb/fileUploadPage,如果 Spring Web 應用程式一切正常,您將看到以下螢幕。

Spring File Upload

提交所需資訊後,單擊提交按鈕提交表單。如果 Spring Web 應用程式一切正常,您應該看到以下螢幕。

Spring File Upload Result
廣告

© . All rights reserved.