概述:
给定一个网络文件 url , 下载文件到浏览器缓存, 完毕后转换其为 blob / File 对象
背景:
项目中现有的发送文件接口, 以及云信 web 端发送文件, 不支持发文件 url , 于是想办法把文件 url 转换为对象
解决过程:
用的 axios (也可以用别的库, 或自己原生 XMLHttpRequest 实现), 设置
// 重点设置 axios
// responseType: 'blob',
// withCredentials: false
// 初始化 axios 实例
const ajaxDownloadFile = axios.create({
baseURL: '',
responseType: 'blob',
withCredentials: false,
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
});
// 请求方法
getFileData(file) {
return new Promise((resolve, reject) => {
ajaxDownloadFile({
url: file.filePath,
method: 'get',
params: {
attname: file.fileName
}
}).then(res => {
this.attachmentDataList[file.id] = res;
resolve(res);
}).catch(error => {
console.error(error);
reject();
});
});
}
补充:
直接用 blob 文件上传, 服务器如果取文件名, 取到的就是 “blob”
如果要加名字, 网上搜了下, 带上 name 转换成 File 文件就行了 — new File([tmpBlob], name)
复制 blob 和 File , 直接 .slice() 复制就行, 复制 File 后重命名 — new File([oldFile.slice()], name);