前端使用文件上传组件,上传电脑上本地文件,上传成功后,修改本地文件内容,提交上传会报错
net::ERR_UPLOAD_FILE_CHANGED
浏览器比较注意文件安全,你修改并保存那就是新的文件(文件修改内容后 file 的本地文件已经丢失),浏览器是不具有新文件的访问权限的,除非你再走一遍选择文件这个流程
上传 beforeUpload 时将 file 转成base64(bese64与本地的文件状态已经无关了),再转成file。
保存 base64 格式
const reader1 = new FileReader();
reader1.readAsDataURL(file);
reader1.onload = e => {
this.base64Excel = e.target.result;
};
base64 转 file 方法
base64ConvertFile (urlData, filename) { // base64转file
var arr = urlData.split(',');
var type = arr[0].match(/:(.*?);/)[1];
var fileExt = type.split('/')[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([ u8arr ], filename, {
type: type
});
},
最后把转出来的 file 通过 formdata 上传
let excel = new FormData();
let form = this.base64ConvertFile(this.base64Excel, this.excelFile.name);
excel.append('file', form);
点击上传时给出文件修改的提示
this.file.slice( 0, 1 ) // only the first byte
.arrayBuffer() // try to read
.then( () => {
// 文件没改变,在这里可以发请求了
console.log( 'should be fine' );
axios({.........})
} )
.catch( (err) => {
// 文件有问题,在这里终止掉
console.log( 'failed to read' );
this.file = null; // 把缓存的file清空
} );
https://www.cnblogs.com/yibottlec/p/15405758.html