java 批量上傳檔案
需要 自行下載 commons的包
jsp 部分
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html><head>
<title>檔案批量上傳</title>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
<form id="batchUploadRiskFileForm" action="../testy/queryCheckDataList" method="Post" enctype="multipart/form-data">
選擇檔案:<input type="file" name="updateFiles" multiple="multiple" />
<input type="submit" />
<p>請在瀏覽檔案時選取至少一個檔案</p>
</form>
</body>
</html>
Java 部分
package com.yihuacomputer.yhcloud.web.action.hr.check;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.yihuacomputer.yhcloud.service.common.base.action.BaseController;
@Controller
@Scope("prototype")
@RequestMapping(value = "testy")
public class UploadAction extends BaseController
{
@RequestMapping(value = "/queryCheckDataList", method = RequestMethod.POST)
@ResponseBody
public ModelMap batchUpdateRiskRule(@RequestParam("updateFiles") MultipartFile[] updateFiles, HttpServletRequest request)
throws IOException
{
ModelMap result = new ModelMap();
Map map = new HashMap();
// 判斷檔案是否為空
if (!(updateFiles.length==0)) {
try {
for (int i = 0; i < updateFiles.length; i++) {
/* // 檔案儲存路徑
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
+ updateFiles[i].getOriginalFilename(); */
//這個updateFiles[i]是MultipartFile的
//MultipartFile 轉換成 File 這裡主要是把多檔案單獨一個一個提取出來單獨處理
//不需要單獨處理 直接批量上傳 使用 updateFiles 就可以了
CommonsMultipartFile cf= (CommonsMultipartFile)updateFiles[i];
DiskFileItem fi = (DiskFileItem)cf.getFileItem();
//獲取流中的單個檔案
File file = fi.getStoreLocation();
result.put("0","上傳成功");
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
serlve.xml 配置
<!-- 上傳檔案攔截,設定最大上傳檔案大小 500M=500*1024**1024*1024(B)=52428800 bytes -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="52428800" />
</bean>