文件需要先下载再转为blob,然后用URL.createObjectURL转为url,在img中实现预览功能,但是如果纯下载到本地就能查看,转为url,点击url会报404,不知道为什么……
export function proviewDownloadFile(url, params, filename, config) {
return service
.post(url, params, {
transformRequest: [
(params) => {
return tansParams(params);
},
],
headers: { "Content-Type": "application/x-www-form-urlencoded" },
responseType: "blob",
...config,
})
.then(async (data) => {
const isBlob = blobValidate(data);
if (isBlob) {
const blob = new Blob([data], { type: "image/jpeg" });
return URL.createObjectURL(blob); // 直接返回 blob 对象
} else {
const resText = await data.text();
const rspObj = JSON.parse(resText);
const errMsg =
errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
throw new Error(errMsg); // 抛出错误
}
})
.catch((r) => {
console.error(r);
throw new Error("下载文件出现错误,请联系管理员!"); // 抛出错误
});
}
export function download(url, params, filename, config) {
downloadLoadingInstance = Loading.service({
text: "正在下载数据,请稍候",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)",
});
return service
.post(url, params, {
transformRequest: [
(params) => {
return tansParams(params);
},
],
headers: { "Content-Type": "application/x-www-form-urlencoded" },
responseType: "blob",
...config,
})
.then(async (data) => {
console.log("blob", data);
const isBlob = blobValidate(data);
if (isBlob) {
const blob = new Blob([data]);
saveAs(blob, filename);
} else {
const resText = await data.text();
const rspObj = JSON.parse(resText);
const errMsg =
errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
Message.error(errMsg);
}
downloadLoadingInstance.close();
})
.catch((r) => {
console.error(r);
Message.error("下载文件出现错误,请联系管理员!");
downloadLoadingInstance.close();
});
}
这是预览下载和下载方法,就多了个返回,很好奇为什么转成了url打开是404,但是下载到本地可以看……
你倒是看下img的src是啥,我估计直接用了返回的promise当src