因專案需要,要開發一個能上傳圖片與文字資訊的 Web 表單頁。
表單頁可上傳圖片,並同時填寫其他文字欄位。
查了資料後發現常見做法是兩段式:先把圖片上傳到伺服器端的某個目錄,伺服器回傳儲存路徑;接著前端把路徑與其他表單資料一起送出,存入資料庫。這樣做的好處是檔案與 business 資料分離,後續要換圖或補圖都比較容易。
<form id="uploadForm" action="/PicSubmit/form" method="post"
enctype="multipart/form-data" class="bootstrap-frm">
<input id="sid" type="text" name="name" />
<input id="fileImage" type="file" name="filename" />
<!-- 用來存放伺服器回傳的圖片路徑 -->
<input id="addressid" type="hidden" name="address" />
<input id="ajaxsub" type="button" class="button"
value="上傳圖片" onclick="fileUpload()" />
<input type="submit" class="button" value="提交表單" />
<input type="reset" class="button" value="重設表單" />
</form>重點有兩個:enctype 必須設為 multipart/form-data,否則後端收不到檔案;若希望一次選多張,在 file 標籤加上 multiple 屬性即可。
另外,那個隱藏的 address 欄位是整個兩段式流程的樞紐——AJAX 上傳成功後把路徑寫進去,之後表單提交時它就會一起被送到後端。
使用 ajaxfileupload.js 這個 jQuery 插件。它的用法與一般 $.ajax() 幾乎相同,差別在於它內部是透過隱藏 iframe 來模擬檔案上傳(這是 XHR 尚未支援 FormData 年代的經典手法)。
呼叫方式:
function fileUpload() {
var inputObject = $("#fileImage").get(0);
if (inputObject.value == "") {
alert("請先選擇需要上傳的圖片");
return false;
}
$.ajaxFileUpload({
url: '/PicSubmit/pic', // 伺服器端請求位址
secureuri: false, // 是否使用安全協議,一般設為 false
type: 'post',
fileElementId: 'fileImage', // 檔案輸入域的 ID
dataType: 'text', // 回傳型別
enctype: 'multipart/form-data',
success: function (data, status) {
data = decodeURI(data); // 後端以 urlencode 編碼中文,這裡解碼避免亂碼
var address = JSON.parse(data);
for (var i = 0; i < address.length; i++) {
ajaxfile_onSuccess(address[i]);
// 自訂回呼中要把伺服器回傳的路徑寫進隱藏欄位,見下方 writeHide
}
},
complete: function (xmlHttpRequest) {
// 上傳一次後原生的 file 標籤會失效,替換成新標籤可解此問題
inputObject.replaceWith('<input type="file" id="fileImage" name="fileImage" />');
},
error: function (data, status, e) {
alert("無法連接到伺服器");
}
});
}
function writeHide(data) {
if ($("#addressid").get(0).value == "") {
$("#addressid").get(0).value = data.newName;
} else {
$("#addressid").get(0).value = $("#addressid").get(0).value + "," + data.newName;
}
}writeHide() 的邏輯是:第一次寫入直接指派,之後則以逗號串接,支援多張圖片的情況。
首先是 Spring MVC 設定檔:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:p="https://www.springframework.org/schema/p"
xmlns:context="https://www.springframework.org/schema/context"
xmlns:mvc="https://www.springframework.org/schema/mvc"
xsi:schemaLocation="
https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-3.1.xsd
https://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- 靜態資源 -->
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/image/**" location="/image/" />
<context:component-scan base-package="web" />
<bean id="defaultAnnotationHandlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean id="annotationMethodHandlerAdapter"
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<!-- 讓 SpringMVC 支援圖片上傳:這段是必須的 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760" /> <!-- 上限 10MB -->
<property name="defaultEncoding" value="UTF-8" />
<property name="resolveLazily" value="true" />
</bean>
<!-- 超過大小限制時的處理 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">
error_fileupload
</prop>
</props>
</property>
</bean>
</beans>CommonsMultipartResolver 這段設定是關鍵,少了它後端根本收不到前端送來的檔案。而 SimpleMappingExceptionResolver 之所以必要,是因為檔案過大時 Spring 在進入 Controller 之前就會拋出例外,若沒有對應處理,使用者只會看到一片空白。
接著在 web.xml 加上編碼過濾器,避免中文檔名出問題:
<!-- 支援傳輸中文字元 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>@RequestMapping(value = "/pic")
@ResponseBody
public String submitPic(
@RequestParam(value = "filename", required = false) MultipartFile[] fileImage,
HttpServletRequest request) {
if (fileImage == null) {
return "[]";
}
return picSaveService.savePic(fileImage);
}這裡有個容易出錯的地方:如果前端 input 標籤有 multiple 屬性,參數型別要寫 MultipartFile[];若沒有,就是單一檔案,寫 MultipartFile 即可。型別寫錯會導致檔案永遠是 null。
public String savePic(MultipartFile[] fileImage) {
String oldName = "";
String newName = "";
String extension = "";
// 以時間戳命名,避免同名覆蓋
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
List<PicConfirmData> resultList = new ArrayList<PicConfirmData>();
// 從設定檔讀取儲存路徑
String path = Parameters.getInstance()
.getDatabaseProps()
.getProperty("pic_save_dir");
for (int i = 0; i < fileImage.length; i++) {
oldName = fileImage[i].getOriginalFilename();
extension = oldName.substring(oldName.lastIndexOf("."));
newName = sdf.format(new Date()) + extension;
File target = new File(path, newName);
if (!target.exists()) {
target.mkdirs();
}
try {
fileImage[i].transferTo(target);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// 只存名稱,路徑已知,可節省資料庫空間
PicConfirmData pic =
new PicConfirmData(1, URLEncoder.encode(oldName, "utf-8"), newName);
resultList.add(pic);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return ToolJson.getJsonFromPicConfirmData(resultList);
}回傳給前端的包含原始檔名(用來顯示「儲存成功」的提示)與儲存後的新名稱(寫進隱藏欄位)。之後表單送出時,隱藏欄位的內容會隨其他欄位一起進資料庫,於是「這筆資料對應哪些圖片」的關聯就建立了。
@RequestMapping(value = "/form")
public String submitForm(HttpServletRequest request) {
String sid = request.getParameter("name");
String address = request.getParameter("address"); // 圖片路徑
if (sid != null && address != null) {
if (formDataSaveService.saveForm(sid, address)) {
return "ac";
}
}
return "error";
}檔案較大時,可以先在前端切片成小塊分別上傳,再由伺服器拼接。這個方法待後續補充。
補充建議:如果你今天重寫這個功能,ajaxfileupload.js 那套 iframe 模擬已經可以淘汰了。直接用 FormData 搭配 $.ajax({ processData: false, contentType: false }),程式碼會短很多,也不必替換失效的 file 標籤。同時別忘了在伺服器端加上副檔名白名單與檔案內容驗證,只檢查 Content-Type 並不足以阻擋偽裝的檔案。