js檔案上傳以及js清空input file值
阿新 • • 發佈:2019-01-11
最近專案中遇到檔案上傳的案例, 之前涉及檔案上傳的較少, 今天針對js檔案上傳的案例做一個詳細的教程,方便日後查閱!
本教程從 原生JS, jQuery, 兩處著手簡單介紹檔案上傳案例
1、原生JS
var test= document.getElementById('test'); var formData = new FormData(); formData.append('version_file', test.files[0]); var ajax = new XMLHttpRequest(); ajax.open("post", "test.php", true); ajax.send(formData );
2、jQuery
var formData = new FormData(); var test = $('#test')[0].files[0]; //或者 $('#test').get(0).files[0]); formData.append('version_file', test); $.Ajax({ type: 'POST', url: 'test.php', data:formData, cache: false,//上傳檔案無需快取 processData: false,//用於對data引數進行序列化處理 這裡必須false contentType: false, //必須 success: function(res){ console.log(res) } })
這裡我列印下$('#test') , 解釋下 $('#test')[0].files[0] 的出處,看下圖:
============================================================
============================================================
============================================================
接下來就是上傳完檔案後把input type為file的文字框的檔案資訊清除了
方法有三:
【1】
var test = document.getElementById('test');
test.value = ''; //雖然test的value不能設為有字元的值,但是可以設定為空值
【2】
var test = document.getElementById('test');
test.outerHTML = test.outerHTML; //重新初始化了test的html
【3】有人在部落格提出這種方法,測試無效!
var test = document.getElementById('test');
test.select();
document.selection.clear();
筆者專案是用AngularJS 1進行開發的。據說ng-file-upload外掛也可以上傳檔案,沒有嘗試,親們可以試下!
參考資料: