天天看點

SpringMVC-檔案上傳和異常處理

SpringMVC-檔案上傳和異常處理

 1. 導入檔案上傳的jar包

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
           

2、編寫檔案上傳的JSP頁面

<form action="test/testUpload" method="post" enctype="multipart/form-data">
    選擇檔案:<input type="file" name="load">
        <input type="submit" name="上傳檔案">
</form>
           

3. 編寫檔案上傳的Controller控制器

@RequestMapping(value="/fileupload2")
public String fileupload2(HttpServletRequest request,MultipartFile upload) throws
Exception {
System.out.println("SpringMVC方式的檔案上傳...");
// 先擷取到要上傳的檔案目錄
String path = request.getSession().getServletContext().getRealPath("/uploads");
// 建立File對象,一會向該路徑下上傳檔案
File file = new File(path);
// 判斷路徑是否存在,如果不存在,建立該路徑
if(!file.exists()) {
file.mkdirs();
}
// 擷取到上傳檔案的名稱
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
// 把檔案的名稱唯一化
filename = uuid+"_"+filename;
// 上傳檔案
upload.transferTo(new File(file,filename));
return "success";
}
           

3. 配置檔案解析器對象

<!-- 配置檔案解析器對象,要求id名稱必須是multipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
</bean>
           

繼續閱讀