使用ajax或XMLHttpRequest实现文件上传
前言
方法一使用ajax封装XMLHttpRequest对象,方法二更加原生,直接创建并使用XMLHttpRequest对象,两种方法均使用formData上传文件。
HTML:
<div>
<input type="file" id="file" name="myfile"/>
<input type="button" @click="UploadMyFile()" value="上传"/>
</div>
方法一:使用ajax
AJAX = 异步 JavaScript 和 XML。
UploadMyFile: function () {
let fileObj = document.getElementById("file").files[0]; // js 获取文件对象
console.log('js文件对象:',fileObj);
let url = "http://**********************"; // 接收上传文件的后台地址
let form = new FormData(); // FormData 对象
/*通过append()方法在末尾追加key为deviceID值为this.deviceID的数据*/
form.append('deviceID',this.deviceID);
form.append("F_file", fileObj); // 文件对象
$.ajax({
url:url,
type:'POST',
cache:false,
data:form,
processData: false,
contentType: false
});
console.log('上传的表单:',form);
},
方法二:使用XMLHttpRequest
XMLHttpRequest 对象用于在后台与服务器交换数据。
使用XMLHttpRequest能够:
---- 在不重新加载页面的情况下更新网页。
---- 在页面已加载后从服务器请求数据。
----在页面已加载后从服务器接收数据。
---- 在后台向服务器发送数据。
UploadMyFile: function () {
let fileObj = document.getElementById("file").files[0]; // js 获取文件对象
console.log('js文件对象:',fileObj);
let url = "http://***********************";
// 接收上传文件的后台地址
let form = new FormData(); // FormData 对象
form.append('deviceID',this.editDevice.deviceID);
form.append("F_file", fileObj); // 文件对象
this.xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
this.xhr.open("post", url, true);
/*post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。*/
this.xhr.onerror = this.uploadFailed; //请求失败
this.xhr.onload = this.uploadComplete; //请求完成
this.xhr.send(form); //开始上传,发送form数据
console.log('上传的表单:',form);
},
//上传成功响应
uploadComplete: function (evt) {
console.log('上传成功响应:',evt);
},
//上传失败
uploadFailed: function (evt) {
console.log('上传失败响应:',evt);
},