檔案上傳


如 果您想要進行檔案上傳的動作,則您可以使用實作 org.springframework.web.multipart.MultipartResolver介面的類別,Spring提供 org.springframework.web.multipart.commons.CommonsMultipartResolver與 org.springframework.web.multipart.cos.CosMultipartResolver,分別支援Commands FileUpload及COS FileUpload。

舉個實際的例子,假設您設計了一個FileForm類別:
  • FileForm.java
package onlyfun.caterpillar;

public class FileForm {
private String name;
private byte[] contents;

public void setName(String name) {
this.name = name;
}

public void setContents(byte[] contents) {
this.contents = contents;
}

public String getName() {
return name;
}

public byte[] getContents() {
return contents;
}
}

FileForm中接受檔案上傳的屬性型態是byte陣列,使用者上傳的檔案可以藉由 org.springframework.web.multipart.support.ByteArrayMultipartFileEditor將之 轉換為byte陣列並設定給FileForm,這必須在定義Controller時註冊,例如:
  • UploadController.java
package onlyfun.caterpillar;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.
support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.
mvc.SimpleFormController;

public class UploadController extends SimpleFormController {
private String path;

public UploadController() {
setCommandClass(FileForm.class);
}

protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors)
throws Exception {
FileForm form = (FileForm) command;

String storedPath = path +
System.getProperty("file.separator") +
form.getName();

BufferedOutputStream bufferedOutputStream =
new BufferedOutputStream(
new FileOutputStream(storedPath));

bufferedOutputStream.write(form.getContents());
bufferedOutputStream.close();

return new ModelAndView(getSuccessView(),
"filename", form.getName());
}

protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder)
throws Exception {
super.initBinder(request, binder);
binder.registerCustomEditor(
byte[].class, new ByteArrayMultipartFileEditor());
}

public void setPath(String path) {
this.path = path;
}
}

依以上的設定,檔案上傳後會儲存在指定的目錄下,要使用檔案上傳的功能,您必須在定義檔中加入MultipartResolver的定義,您可以選擇使用 CommonsMultipartResolver或CosMultipartResolver,例如以下使用 CommonsMultipartResolver來定義:
  • mvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="urlMapping"
class="org.springframework.web.servlet.
→ handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/index.do">
indexController
</prop>
<prop key="/upload.do">
uploadController
</prop>
</props>
</property>
</bean>

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

<bean id="indexController"
class="org.springframework.web.servlet.
→ mvc.ParameterizableViewController">
<property name="viewName">
<value>index</value>
</property>
</bean>

<bean id="multipartResolver"
class="org.springframework.web.multipart.
→ commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>1000000</value>
</property>
</bean>

<bean id="uploadController"
class="onlyfun.caterpillar.UploadController">
<property name="formView">
<value>form</value>
</property>
<property name="successView">
<value>success</value>
</property>
<property name="path">
<value>C:\upload</value>
</property>
</bean>
</beans>

在定義檔中,藉由設定UploadController的"path"屬性為"C:\upload",表示上傳後的檔案會儲存在C:\upload目錄之中,接著設計一個index.jsp:
  • index.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Upload Page</title>
</head>
<body>
<form name="uploadForm" enctype="multipart/form-data"
action="/FileUploadDemo/upload.do" method="POST">
上載後檔案名稱: <input name="name" type="text"/><br>
選擇檔案: <input name="contents" type="file"/><br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

在這個頁面中可以設定上傳後的檔案名稱,並可以選擇所要上傳的檔案名稱,success.jsp則設計如下:
  • success.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Upload Success</title>
</head>
<body>
<h1>File: \${filename} upload successfully.</h1>
</body>
</html>

這個專案使用到相依的Commands FileUpload,所以您要在lib目錄中包括commons-fileupload.jar檔案。