后端接口返回blob文件 前端预览
web端文件预览
/**
* 私有桶存储文件特殊处理
* @param dataUrl
* @param preview 是否预览(限pdf)
*/
export function handleWorkorderObs(dataUrl: string, preview?: boolean | null, type?: string) {
getFileDownload(
{fileUrl: dataUrl},
{
responseType: 'blob',
getResponse: true,
ctlType: 'none'
},
).then((res) => {
console.log('current res', res)
if (!res) {
return
}
if(res.response?.headers['content-type']?.includes("image/") && type !='download'){
Modal.confirm({
title: '',
content: <Image src={URL.createObjectURL(res.response.data)} />,
icon:'',
cancelButtonProps: { style: { display: 'none' } },
onOk: () => {
},
});
return
}
const { response } = res;
const filename = response.headers['content-disposition'].split('=')[1];
if(filename?.endsWith('pdf') && preview){
window.open(window.URL.createObjectURL(response.data))
return
}
const a: any = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
let blob = new Blob([response.data], {
type: 'application/x-zip-compressed',
});
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = decodeURI(filename);
a.click();
window.URL.revokeObjectURL(url);
})
}
小程序预览
/**
* 私有桶存储文件特殊处理 预览
* @param dataUrl
*/
export function handleWorkorderObs(dataUrl: string) {
getFileDownload(
{fileUrl: dataUrl},
{
responseType: 'arraybuffer',
// getResponse: true,
// ctlType: 'none'
},
).then((res) => {
console.log('current res', res)
if (!res) {
return
}
const filename =Date.now() + decodeURI(dataUrl?.substring(dataUrl?.lastIndexOf('/') + 1));
console.log('current filename', filename)
const fs = Taro.getFileSystemManager();
const filePath = `${Taro.env.USER_DATA_PATH}/${Date.now()}${filename}`;
// 将二进制数据写入文件
fs.writeFile({
filePath,
data: res,
encoding: 'binary',
success: function () {
Taro.openDocument({
filePath: filePath,
success: function () {
console.log('打开文档成功',filePath,)
},
fail: function(err){
console.log('err----', err)
}
})
},
fail: function (err) {
console.log('写入文件失败', err)
}
})
})
}