原生js创建 input 上传标签
var file;
(function () {
var input = document.createElement('input');
input.type = 'file';
input.id = 'file';
input.name = 'file';
input.style.cssText = `
width: 400px;
opacity: 0;
position: absolute;
top: 20px;
left: 64px;
`;
document.getElementById('fileupload').appendChild(input)
input.onchange = (e) => {
file = e.target.files[0];
console.log('file', file)
}
})()
??
jquery ajax上传文件
??这个handleUpload 方法可以是 element 绑定的自定义上传方法,如果是element 自定义的上传方法,那么参数就得改变一下;
<el-upload
class="upload-demo"
action=""
:http-request="handleUpload"
:file-list="fileList"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
function handleUpload(file) {
let fileDatas = new FormData();
fileDatas.append('files', file);
$.ajax({
url: "/api/xxx/upload",
type: "POST",
data: fileDatas,
contentType: false,
processData : false,
success: res => {
console.log('上传成功res', res);
}
})
}
??
原生ajax上传文件
function handleUpload() {
let formData = new FormData();
formData.append("file", file);
let xhr = new XMLHttpRequest();
xhr.open("POST", "/api/xxx/upload", true);
xhr.ontimeout = function() {
alert("请求超时");
};
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
const res = JSON.parse(xhr.responseText);
console.log('上传成功', res)
if(res.state == 'success') {
alert("上传成功");
} else {
alert(res.message);
}
} else {
alert("上传失败");
}
}
};
xhr.send(formData);
}
?? ?? ?? 如有不足,望大家多多指点! 谢谢!
|