這是很簡單。。 HTML <div> <input type="file" id="myfile"> <input type="button" value="上傳" onclick="HeadPortraitPicture()"> </div> JS代碼 function HeadPortraitP ...
這是很簡單。。
HTML
<div>
<input type="file" id="myfile">
<input type="button" value="上傳" onclick="HeadPortraitPicture()">
</div>
JS代碼
function HeadPortraitPicture()
{
if (document.getElementById('myfile').files[0] != null) {//判斷上傳的文件是否為空
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('myfile').files[0]);//這是獲取上傳的文件
var xhr = new XMLHttpRequest();
xhr.open("POST", "/DEMO/SettingCode/Exceltolead?type=doExcel");//要傳到後臺方法的路徑
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);//返回來的數據
xhr.addEventListener("error", uploadFailed, false);//返回異常
xhr.addEventListener("abort", uploadCanceled, false);//返回連接異常
xhr.send(fd);//放入文件發送到後臺
}
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
//var percentComplete = Math.round(evt.loaded * 100 / evt.total);//可以在這裡接收進度條數據
}
else {
alert("無法計算!");
}
}
function uploadComplete(evt) {
/* 伺服器返回數據*/
var message = evt.target.responseText;//接收返回來的數據
}
function uploadFailed(evt) {
alert("上傳出錯.");
}
function uploadCanceled(evt) {
alert("上傳已由用戶或瀏覽器取消刪除連接.");
}