1.html
<input type="file" accept="image/*" ref="fileToUpload" name="fileToUpload" id="fileToUpload" style="opacity: 0" @change="uploadFile"/>
2.js
export default {
name: 'headImg',
components: {},
data () {
return {
avatarUrl: 'http://******', // 文件上传路径
avatarSize: 2097152, // 2M,文件上传大小
};
},
created () {},
methods: {
/* 上传 */
uploadFile () {
let file = this.$refs.fileToUpload.files[0];
if (file.size > this.avatarSize) { // 文件大小超出限制
......
} else {
let fd = new FormData();
fd.append('avatar', this.$refs.fileToUpload.files[0]);
let xhr = new XMLHttpRequest();
xhr.addEventListener('progress', this.uploadProgress, false);
xhr.addEventListener('load', this.uploadComplete, false);
xhr.addEventListener('error', this.uploadFailed, false);
xhr.addEventListener('abort', this.uploadCanceled, false);
xhr.open('POST', this.avatarUrl);
xhr.send(fd);
}
},
uploadProgress (evt) {
console.log('上传中', evt);
},
uploadComplete (evt) {
console.log(evt); // 获取上传成功后返回的结果
},
uploadFailed (evt) {
console.log('上传失败', evt);
},
uploadCanceled (evt) {
alert('上传取消');
}
}
};
3.该过程中遇到一个413报错,该报错的原因是:
前端和后台设置的最大限制都是2M,内部服务器后来也修改为4M上传大小,但是还是报错。
最后发现外网进入内网限制了上传大小为1M,我所使用的文件上传路径是外网路径。。。修改了外网限制后则正常。