form表單提交批量上傳檔案,不重新整理不跳轉頁面
阿新 • • 發佈:2019-01-07
jsp:
<form action="inImg.do" method="post" enctype="multipart/form-data" target="nm_iframe"> <table> <tr> <td width="100" align="right">照片:</td> <td> <input type="file" id="btn_file" name="theFile" multiple/></td> </tr> </table> <input type="submit"> </form> <iframe id="id_iframe" name="nm_iframe" style="display:none;"/>
controller:
/** * 儲存前臺選擇的檔案到資料庫 */ @RequestMapping("inImg.do") public void inImg(HttpServletRequest request,@RequestParam(value = "theFile") MultipartFile[] files) throws Exception{ for(MultipartFile file:files){ UserMsg userMsg = new UserMsg(); userMsg.setMessage("我在上傳前臺選擇的圖片到資料庫"); userMsg.setPicture(file.getBytes()); userMsg.setUserName("fzq"); loginService.saveImg(userMsg); } }
要點1:在input標籤中加入multiple屬性,並在controller中用MultipartFile[]陣列來接收,實現批量
要點2:加入一個隱藏的iframe,設定input標籤的target屬性,實現form表單提交不重新整理不跳轉頁面
之後:
發現這樣寫,我點選其它input按鈕時,總是報錯,說這個onclick方法總是沒有定義,原因暫時還沒有找到
所以換了一種寫法(controller可以不改):
<div> 使用者名稱:<input type="text" id="userName"/><br> 密碼:<input type="text" id="userPassword"><br> <input type="button" value="登入" onclick="fnCommit()"/> <input type="button" value="註冊" onclick="TofnSaveUser()"/> <input type="button" value="儲存本地圖片" onclick="fnTest()"/> <input type="button" value="下載資料庫圖片" onclick="fnCC()"/> <img src="<%=request.getContextPath() %>/loginController/showImg.do"/> </div> <form action="inImg.do" method="post" enctype="multipart/form-data" id="registSubmit" > <input type="file" id="btn_file" name="theFile" multiple style="display:none"/> <input type="submit" style="display:none"> </form> <div> <input type="button" value="選擇檔案" onclick="fnChoseFile()"> <input type="button" value="上傳" onclick="fnImPortData()"> </div>
<script src='<%=request.getContextPath() %>/js/jquery-form.js'></script>
function fnImPortData(){
var filecheck = document.getElementById("btn_file").value;
if(filecheck){
var options = {
url: "inImg.do",
dataType:"text",
type:"post",
success:function(responseText){
}
}
$("#registSubmit").ajaxSubmit(options);
}
}
function fnChoseFile() {
document.getElementById("btn_file").click();
}