用axios實現上傳圖片和文件功能 , 首先html頁面 :
<input type='text' v-moudel='username' />
<input type='file' id='file' />
<button @click='upload'>上傳</button>
一個text輸入框 , 一個文件輸入框
js :?
upload: function() {
? ? ? var data = new FormData();
? ? ? data.append('username', this.username);
? ? ? data.append('img', document.getElementById('file').files[0]);? ? ? ? //因為傳入的文件可能有很多 , 一個一個傳輸
? ? ? var config = {? ? ? ? // 這個函數是表示進度的 ,??在這里打印 percentCompleted ( 0-100 ) , 可以根據他的值做進度條
? ? ? ? onUploadProgress: function(progressEvent) {?
? ? ? ? ? var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
? ? ? ? ? console.log(percentCompleted);
? ? ? ? }??
? ? ? };
? ? ? axios.post('/upload/server', data, config)? ? ? ? //提交 不能用get請求
? ? ? ? .then(function (res) {
? ? ? ? ? console.log(res);
? ? ? ? })
? ? ? ? .catch(function (err) {? ? ? ? // catch 錯誤并打印
? ? ? ? ? console.log(err);
? ? ? ? });
? ? }
? }
第二種方法不是用ajax , 是用表單仿的 ajax , 缺點是沒辦法做進度條 , 是比較老的方法 , 但是寫起來比較簡單
<form target=' fakeajax ' method=' post ' enctype=' multipart/form-data ' action=" http://localhost:3000/upload/server " >
? ? <input type = "text" name = "username" />
????<input type = 'file' name = "username" />
? ? <button type=' submit '>上傳</button>
????<iframe id=' fakeajax ' name = " fakeajax " style = " display:none " ></iframe>
</form>