前言
這裏用了2個JS插件,一個是Jquery原生js,我的版本是jquery-1.7.2.min.js,另一個是jquery.form.js。這個form.js 是關鍵,不可少哦。另外,
我的服務器端用的是Play Framework,版本是2.1。下面是代碼部分,貼出的是關鍵部分:
1.前端代碼
html:
<form id="form1" method="POST" action="/image/upload" ENCTYPE="multipart/form-data"> <input id="uploadFile" type="file" name="myfile" /> </from>
Javascript:
$("#uploadFile").change(function(){ var message = "t"; $("#form1").ajaxSubmit({ method : "POST", success : function(data){ //成功 if(data == "ok"){
alert("上傳成功")
}else{ alert("上傳失敗"); }
}, error : function(){ alert("網絡錯誤,請稍後重新嘗試!"); } }); });
2.服務端代碼
public static void upload(File myfile){ String msg = "fail"; try{ //圖片寫入路徑,此處我的位置是項目的根目錄 File temp = new File(myfile.getName()); //輸入文件流 FileInputStream input = new FileInputStream(myfile); //輸出文件流 FileOutputStream out = new FileOutputStream(temp); //每次寫入的字節的大小 byte [] b = new byte[1024]; //文件長度 int n; while((n=input.read(b)) != -1){ //寫入字節 out.write(b, 0, n); } input.close(); out.flush(); out.close(); msg = "ok"; }catch(Exception e){ Logger.error("Image.upload()", e.getMessage()); } renderJSON(msg); }