1. 程式人生 > >SpringMVC之文件上傳

SpringMVC之文件上傳

blog cnblogs work info tps spring容器 struts mem 上傳文件

使用Springmvc上傳文件相較於傳統的java編程和struts2來說非常簡單,只需要在Spring容器中配置org.springframework.web.multipart.commons.CommonsMultipartResolver這個類即可。

Spring容器配置:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="
102400000" /> <property name="maxInMemorySize" value="4096" /> <property name="defaultEncoding" value="utf-8" /> </bean>

註意:該id="multipartResolver"不能寫成commonsMultipartResolver及其他形式,否則將會報錯。

Java代碼:

@RequestMapping("test8")
public String test8(MultipartFile file, HttpSession session) throws IOException {
    
// 獲取文件名 String filename = file.getOriginalFilename(); // 獲取存儲上傳文件的路徑 String path = session.getServletContext().getRealPath("/WEB-INFO/upload"); // 判斷該路徑是否存在 File f = new File(path); if (!f.exists()) { f.mkdirs(); } // 創建目標文件 File descFile = new File(path, filename);
// 將源文件上傳到目標文件 file.transferTo(descFile); return SUCCESS; }

SpringMVC之文件上傳