前端JSP頁面代碼片斷:前端
<!-- springMVC包裝類上傳文件 -->
<form name="uploadFiles" id="uploadFiles" action="http://sdoa.vaiwan.com:8081/sdoa/file/uploadFiles.do" enctype="multipart/form-data" method="post">
<div id="addFilelist">
<div id="file_0">
<input type="file" name="file_0" multiple="multiple" >
</div>
</div>
<input type="button" id="btn_add_file" value="增長一行" onclick="add_file()">
<input type="submit" value="上傳" >
</form>
<script>
j=1;
function add_file(){
document.getElementById("addFilelist").innerHTML+='<div id="file_'+j+'"><input name="file_'+j+'" type="file" /><input type="button" value="刪除" onclick="del_file('+j+')"/></div>';
j = j + 1;
}
function del_file(o){
document.getElementById("addFilelist").removeChild(document.getElementById("file_"+o));
}
</script>
java後臺SpringMVC uploadFilesController類代碼
@RequestMapping("uploadFiles.do")@ResponseBodypublic String uploadFiles(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException { System.out.println("*********************進入uploadFiles(HttpServletRequest request, HttpServletResponse response)方法********************"); String returnPath = ""; //建立一個通用的多部分解析器 將當前上下文初始化給CommonsMultipartResolver多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //判斷 request 是否有文件上傳,即多部分請求 檢查form中是否有 enctype="multipart/form-data"屬性值 if(multipartResolver.isMultipart(request)){ //轉換成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; //取得request中的全部文件名 Iterator<String> iter = multiRequest.getFileNames(); while(iter.hasNext()){ //記錄上傳過程起始時的時間,用來計算上傳時間 int pre = (int) System.currentTimeMillis(); //取得上傳文件 MultipartFile file = multiRequest.getFile(iter.next()); if(file != null){ //取得當前上傳文件的文件名稱 String myFileName = file.getOriginalFilename(); //若是名稱不爲「」,說明該文件存在,不然說明該文件不存在 if(myFileName.trim() !=""){ System.out.println(myFileName); //重命名上傳後的文件名 String fileOriginalName = file.getOriginalFilename(); String newFileName=UUID.randomUUID()+fileOriginalName.substring(fileOriginalName.lastIndexOf(".")); String savedPath = request.getSession().getServletContext().getRealPath("/") + "uploadFiles/";//獲取服務器指定文件存取路徑 File saveDir = new File(savedPath); if (!saveDir.exists()){ saveDir.mkdirs(); } File savedFile = new File(savedPath,newFileName); System.out.println(savedPath+"*********"+savedFile); boolean isCreateSuccess = savedFile.createNewFile(); if(isCreateSuccess){ file.transferTo(savedFile); //轉存文件 } if (returnPath != null && returnPath != ""){ returnPath = returnPath +";"+ savedFile; }else { returnPath = returnPath + savedFile; } } } //記錄上傳該文件後的時間 int finaltime = (int) System.currentTimeMillis(); System.out.println(finaltime - pre); } return returnPath; } return "方法執行錯誤";}很差的地方就是前端頁面每次點擊添加一行時頁面會刷新一下,先記錄下來,下一步準備使用ajax+input的multiple="multiple"屬性實現異步的多文件上傳。