1. 程式人生 > >SpringMVC使用進階-檔案上傳

SpringMVC使用進階-檔案上傳

如今檔案上傳的方式已經是遍地開花,各種五花八門的檔案上傳有的時候著實讓人難以抉擇,如果是使用springmvc也不用為檔案上傳而發愁,springmvc的檔案上傳比struts2的那個還要簡單,就是寥寥無幾的一點程式碼就能解決上傳。

1  修改之前的配置檔案

spring主要是編寫配置檔案比較麻煩,配置檔案正確是程式正確執行的關鍵,同樣的springmvc如果要支援檔案上傳也需要加上如下配置;

<!-- 檔案上傳相關配置 -->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  
	    <property name="defaultEncoding" value="gbk"/> <!-- 預設編碼 (ISO-8859-1) -->  
	    <property name="maxInMemorySize" value="10240"/> <!-- 最大記憶體大小 (10240)-->  
	    <property name="uploadTempDir" value="/temp/"/> <!-- 上傳後的目錄名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->  
	    <property name="maxUploadSize" value="-1"/> <!-- 最大檔案大小,-1為無限止(-1) -->  
    </bean>


2  檔案上傳介面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>檔案上傳</title>
</head>
<body>
<form action="upload.do"  method="post" enctype="multipart/form-data">
	名稱:<input type="text" name="name" /><br><br>
	選擇檔案:<input type="file" name="image" /><br><br>
	<input type="submit" value="確認上傳"/>
</form>
</body>
</html>

無論jsp、php、asp.net上傳檔案一般都通過表單上傳,而且還必須有enctype="multipart/form-data",否則檔案將無法上傳成功,還需要注意的一點就是springmvc的上傳實現使用的是commons-io,因此相應的jar包也不能少。

3  檔案上傳控制器

package org.hncst.controller;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class FileUploadController  implements ServletContextAware{
	private ServletContext servletContext;
	public ServletContext getServletContext() {
		return servletContext;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	@RequestMapping(value="/upload.do", method = RequestMethod.POST)
	public String uploadFile(String name,@RequestParam("image") CommonsMultipartFile file) {
        String path=this.servletContext.getRealPath("/upload");
        //取得原始的檔名
        String fileName=file.getOriginalFilename();
        //取得檔案的字尾(包含點號)
        String fileExt=fileName.substring(fileName.lastIndexOf("."));
        //使用時間戳給檔案命名
        File file2=new File(path,new Date().getTime()+fileExt);
        //將上傳的檔案儲存起來
        try {
			file.getFileItem().write(file2);
		} catch (Exception e) {
		
			e.printStackTrace();
			
			return "redirect:uploadFailure.jsp";
		}
		return "redirect:uploadSuccess.jsp";
	}

	
}

這個上傳的實現和struts有比較相似,都要取得上下文物件,struts和springmvc的做法大體類似,控制器都需要實現ServletContextAware介面