jquery ajax 無重新整理上傳檔案到servlet
阿新 • • 發佈:2019-02-06
刪除檔案的表單要加入如下enctype屬性:
<form id="upload" enctype="multipart/form-data"><!--//由於使用ajax上傳,不用加action和method屬性-->
要實現無重新整理上傳檔案首先要阻止submit按鈕提交表單,在submit按鈕新增onclick屬性:
<button type="submit" onclick="return false">登入</button><!-- 用input也可以 -->
這樣寫這個提交按鈕就失效了。
接著需要在按下提交按鈕時執行ajax操作,將標籤改為:
<button type="submit" onclick="return upload()">登入</button><!-- 用input也可以 -->
js函式如下:
function upload() { //提交前先對檔案進行檢查,<input id="file" type="file"> var file = $("#file")[0].files;//獲取上傳控制元件中的檔案列表 if(file.length == 0){//沒有指定檔案 alert("請選擇檔案"); } else if(file.length>1){//檔案多於一個,這個根據具體需求,我這裡限定只能傳一個 alert("只能上傳一個檔案"); } else{ file = file[0];//確定只有一個檔案了,取得這個檔案物件 if(file.type! = "image/png"&&file.type!="image/jpeg"&&file.type!="image/gif"){//檢查檔案格式,根據具體需求 alert("檔案格式錯誤"); } else if(file.size>1024*500){//檢查檔案大小,這裡限定了檔案大小不超過500KB alert('檔案太大'); } else{ var formData=new FormData($('#upload')[0]);//取得表單的所有資料 document.body.append($("<div id='shadow' style='width:100%;height:100%;"+ "position:fixed;top:0px;left:0px;background-color:rgba(100,100,100,0.3);"+ "z-index:"+Number.MAX_SAFE_INTEGER+"'></div>")[0]); //執行ajax之前在當前頁面加入一個遮罩層,表示正在上傳 $.ajax({ url:"../Upload", method:"post", timeout:5000, data:formData, processData:false, contentType:false,//這兩行是上傳檔案時才需要加的 success:function(data){ if(data=="ok"){ //上傳成功 } else{ alert(data);//列印伺服器返回的錯誤資訊 } }, error:function(data){ alert("上傳失敗"); }, complete:function(){ $("#shadow").remove();//結束時移除遮罩層 } }); } } return false;//還記得它的作用嗎?阻止submit按鈕提交表單 };
servlet程式碼:
servlet需要新增一個註解@MultipartConfig,也可以用web.xml配置,這裡不做介紹
@WebServlet("/Upload") @MultipartConfig public class UploadServlet extends HttpServlet { ................ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final Part filePart = request.getPart("file"); if (filePart == null) { response.getWriter().print("未指定檔案"); return; } if (filePart.getSize() > 1024 * 500) { response.getWriter().print("檔案太大"); return; } String filename = filePart.getSubmittedFileName();//獲取上傳檔名 String realPath = this.getServletContext().getRealPath("/upload"); //獲取web目錄的真實物理路徑,檔案將儲存在upload資料夾下 File dir=new File(realPath); if(!dir.exist()){ dir.mkdir();//如果目錄不存在,則建立 } filePart.write(realPath + "/" + filename);//將檔案寫入磁碟 response.getWriter().print("ok"); } ................. }