以上传图片为例:
在html中我们这么写:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="fileform" enctype="multipart/form-data">
<input type='file' name='file'/><br/>
<input type='submit' value='submit'/>
</form>
</body>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" type="text/javascript"></script>
<script>
/*上传文件*/
document.querySelector("#fileform").addEventListener("submit", function(event) {
var formdata=new FormData($("#fileform")[0]);
$.ajax({
type : 'post',
url :host+'/file/uploadFileLocal?xxxxxxxxxxxxxx',//地址改为后台给的上传地址
data : formdata,
cache : false,
processData : false, // 不处理发送的数据,因为data值是Formdata对象,不需要对数据做处理
contentType :false, // 不设置Content-type请求头
success : function(res){
//上传成功
},
error : function(x){
//上传失败
}
})
event.preventDefault();
})
</script>
</html>
那么在框架中频繁使用,给直接给它封装好,下面可以直接复制使用:
export const upload=(option)=>{
const xhr = new XMLHttpRequest();//定义上传方式
if (option.onProgress && xhr.upload) {
xhr.upload.onprogress = function progress(e) {
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
}
option.onProgress(e);//上传进度,也是上传成功后回调
};
}
const formData = new FormData();
formData.append('file', option.file,option.file.name);
xhr.onerror = function error(e) {
option.onError(e);//失败返回
};
xhr.onload = function onload() {
if (xhr.status < 200 || xhr.status >= 300) {
return option.onError(getError(option, xhr), getBody(xhr));
}
option.onSuccess(getBody(xhr), xhr);//成功返回函数
};
xhr.open('post', option.action, true);
if (option.withCredentials && 'withCredentials' in xhr) {
xhr.withCredentials = true;
}
const headers = option.headers || {};//定义请求头
if (headers['X-Requested-With'] !== null) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
for (const h in headers) {
if (headers.hasOwnProperty(h) && headers[h] !== null) {
xhr.setRequestHeader(h, headers[h]);
}
}
xhr.send(formData);
return {
abort() {
xhr.abort();
},
};
};
export default upload;
使用方式:
upload({
file: options.file,
filename: options.file.name, //文件名称
headers: {
//header对象
},
action:'',//上传文件的地址
onError(e){
//失败了
},onSuccess(e){
//成功了
}
})
上传格式预览: