大家好
ajax 上傳檔案方式其實有很多種
那我習慣用 jquery 方式去上傳
我參考這邊:
jQuery Ajax File Upload
https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload
這邊我提供我常用的方法給大家參考
主要是 新增 Upload 物件 以及 ajax 送出 以及事件聆聽的設定而已
給大家參考囉
//這邊我是綁定一個按鈕 按下去就觸發 按下去uploadFile的動作
//uploadFile 是這樣的物件 <input style="display: none" id="uploadFile" name="uploadFile" type="file" accept=".mat" />
matF2.uploadMat = function(){
$("#uploadFile").click();
}
//當使用者選擇檔案 則觸發 upload
$("#uploadFile").on("change", function (e) {
var file = $(this)[0].files[0];
var upload = new Upload(file);
upload.doUpload();
});
//初始化物件 與設定值
var Upload = function (file) {
this.file = file;
};
//可選用資料
Upload.prototype.getType = function() {
return this.file.type;
};
//可選用資料
Upload.prototype.getSize = function() {
return this.file.size;
};
//可選用資料
Upload.prototype.getName = function() {
return this.file.name;
};
//開始上傳
Upload.prototype.doUpload = function () {
var that = this;
//新增表單物件來送出
var formData = new FormData();
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
//呼叫 mask 讓使用者等待(這邊為自己去定義的動作)
jQuery('body').mask("上傳中,請稍後...<sapn class=\"countPimg\">0%</span>");
//ajax 上傳
$.ajax({
type: "POST",
//上傳位置
url: "/test2/matUpload/",
//增加事件聆聽進度
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
//成功之後 (指的是傳送到SERVER為200 不一定 SERVER 100%有接收成功,可能檔案在SERVER驗證會失敗)
success: function (data) {
//取得回傳結果
if (data.result != 1) {
alert('ERROR 833962 發生錯誤:'+data.msg);
jQuery('body').unmask();
} else {
//都正確
alert("上傳完成!");
location.reload();
}
},
//錯誤 上傳後 不是 200狀態
error: function (error) {
console.log(error);
alert("上傳失敗!");
jQuery('body').unmask();
},
async: true,
data: formData,
cache: false,
contentType: false,
//SERVER 回傳格式是 JSON
dataType:"json",
processData: false,
//time out 時間
timeout: 60000,
});
};
//聆聽進度事件
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//這邊自訂自己要的提醒方式
jQuery('.countPimg').html(percent+'%');
};

留言板
歡迎留下建議與分享!希望一起交流!感恩!