檔案上傳及多檔案上傳
阿新 • • 發佈:2018-12-24
一、單檔案上傳
注:
1.我這裡使用的是springmvc,所以在配置檔案中,要新增如下配置(並新增commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar)
2.springmvc其餘配置參照之前文章
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxInMemorySize" value="100"></property> <property name="uploadTempDir" value="fileresouce/temp"></property><!-- 預設資料夾 --> </bean>
表單:
<form action="###" id="sform" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="myfile"/>
<input type="submit" value="上傳" >
</form>
處理:
#public Boolean upload(@RequestParam("myfile") MultipartFile file, HttpServletRequest request, HttpServletResponse response) { String filePath = ""; if (!file.isEmpty()) { try { filePath = request.getSession().getServletContext().getRealPath("/") + "/file/" + file.getOriginalFilename();// 檔案絕對路徑(包括檔名) String filerootpath = request.getSession().getServletContext().getRealPath("/") + "/file/";// 資料夾路徑 // 如果該資料夾不存在,則手動建立 File filerootpathdic = new File(filerootpath); if (!filerootpathdic.exists()) { filerootpathdic.mkdirs(); } file.transferTo(new File(filePath));// 上傳檔案 } catch (Exception e) { e.printStackTrace(); } } return true; }
二、多檔案上傳
表單:
處理:<form action="${basepath}/fileupload/upload.do" id="sform" method="post" enctype="multipart/form-data"> <input type="file" name="myfile" id="myfile" <span style="color:#ff0000;"><strong>multiple="multiple"</strong></span> /> <input type="submit" id="btn" value="上傳" > </form>
public Boolean upload(@RequestParam("myfile") <strong><span style="color:#ff0000;">MultipartFile[] file</span></strong>,HttpServletRequest request,HttpServletResponse response){
<span style="color:#ff0000;"><strong>for(MultipartFile f:file){</strong></span>
String filePath="";
if (!f.isEmpty()) {
try {
filePath= request.getSession().getServletContext().getRealPath("/")+ "/file/"+ f.getOriginalFilename();
String filerootpath = request.getSession().getServletContext().getRealPath("/")+ "/file/";
File filerootpathdic = new File(filerootpath);
if(!filerootpathdic.exists()){
filerootpathdic.mkdirs();
}
f.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}
注:
1.多檔案上傳與單檔案上傳實質是一樣的,
區別:1)標籤中新增multiple屬性;2)後臺用陣列接收
2.前臺表單中name="myfile"的值要與後臺@RequestParam("myfile")的引數名稱要一致,否則會報400錯誤
3.我這兒上傳檔案,不限型別,如有限制,在配置檔案中新增相應條件即可