跳到主要内容

图片上传

HTML

<input type="file" multiple accept="image/jpeg,image/png," name="multipleFile" id="multipleFile"/>

JavaScript

FormData

$(function() {
$("#multipleFile").change(function(){
var formData = new FormData();
var files = this.files;
for(var i = 0; i < files.length; i++) {
formData.append('files[]', files[i]);
}
axios.post('/upload', formData, {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
},
transformRequest: [function(data) {
return data
}],
onUploadProgress: function(e) {
var percentage = Math.round((e.loaded * 100) / e.total) || 0;
if (percentage < 100) {
console.log(percentage + '%'); // 上传进度
}
}
}).then(function(resp) {
console.log(resp.data); // {code: 200, description: "", detail: null}
})
})
})

Blob

const file = files[0]; //this will not work.
const file = new Blob([files[0]]); // kind of works and choses stream as content type of file (not request)
const file = new Blob([files[0]], { type: 'image/png' });// WORKS much better (if you know what MIME type you want.

const formData = new FormData();
formData.append('test', file, file.filename);
axios.post('...url...', formData, {}).then(...).catch(...);

其他

  const handleImageUpload = acceptedFiles => {
return new Promise((resolve, reject) => {
const file = new Blob([acceptedFiles]);
const formData = new FormData();
formData.append('emoji', file, acceptedFiles['name']);
axios.post('/emoji', formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'image/*',
},
transformRequest: [
function(data) {
return data;
}],
onUploadProgress: function(e) {
let percentage = Math.round((e.loaded * 100) / e.total) || 0;
if (percentage < 100) {
console.log(percentage + '%'); // 上传进度
}
},
}).then(function(resp) {
resolve(resp.data.url);
});
});
};


参见