给出一个上传文件时不用刷新页面的方案,要求写出关键部分的js代码。
<input id="upload" type="file" /> <button id="upload-btn"> upload </button>
document.getElementById('upload-btn').onclick = function(){
varinput = document.getElementById('upload');
varfile = input.files[0];
varformData = newFormData();
forData.append('file',file);
fetch({
url:'/upload',
mothod:'POST',
body:formData
})
.then((d)=>{
console.log('result is',d);
alert('上传完毕');
})
}
$(document).ready(function() {
$("#inputfile").change(function() {
//创建FormData对象
var data = new FormData();
//为FormData对象添加数据
//
$.each($('#inputfile')[0].files, function(i, file) {
data.append('fileData', file);
});
$.ajax({
url: 'url',
type: 'POST',
data: data,
dataType: 'json',
***: false,
contentType: false, //不可缺
processData: false, //不可缺
success: function(data) {
if (data.success == true) {
var img = $("#img-show");
if (img.children('img').length != 0) {
img.children('img').attr('src', data.file_path);
var img_input = '<input type="hidden" name="picture" id="picture" value="' + data.file_path + '">'
img.append(img_input);
} else if (img.children('img').length == 0) {
var img_show = '<img src="' + data.file_path + '" width="135" height="75">';
img.append(img_show);
var img_input = '<input type="hidden" name="picture" id="picture" value="' + data.file_path + '">'
img.append(img_input);
}
}
}
});
});
});