Angular 响应中的Blob()不是';不显示原始图像url,但显示大小和类型
虽然我没有任何错误,但我没有像邮递员那样完美地显示图像。我使用了res.json(),收到了“位置0处的意外标记<”。然后我尝试了res.text(),我可以使用res.blob(),但当我将它与url=url.createObjectURL(blob)一起使用时。我得到了一个不同的文件名,无法从API中检索以显示。 我知道有几个关于堆栈溢出的参考,但与我打算做的不同,而且随着我尝试了这么多选项,它变得越来越复杂Angular 响应中的Blob()不是';不显示原始图像url,但显示大小和类型,angular,laravel,fetch-api,Angular,Laravel,Fetch Api,虽然我没有任何错误,但我没有像邮递员那样完美地显示图像。我使用了res.json(),收到了“位置0处的意外标记
fetch(url, {
method: 'POST',
body: uploadData,
headers: {
// 'X-Requested-With': 'XMLHttpRequest',
// 'Accept': 'application/json',
'Authorization': 'Bearer ' + this.bearerToken,
// 'Content-Type': 'multipart/form-data',
}
}).then(res => res.blob()).then((response) => {
if (response) {
console.log(response);
// const slashIndex = response.lastIndexOf('/');
// const filename = response.substring(slashIndex + 1);
// this.openUploadConfirmDialog(filename, shareOption);
}
}).catch((error) => {
if (error) {
console.log('Error', error);
this.snackBar.open('Unable to upload image, Try again later!', '', {duration: 4000});
}
});
}
});
这是API
这是返回响应;返回
response()->file(storage_path('app/uploads/images/'.$exportName));
谢谢首先,您的API没有任何问题,它编写得很好。问题在于angular fetch API不完整,还塞满了一些不相关的代码。我已经清理了你的代码,并用几行代码重写了它 使用FileReader()是秘密。在您的Laravel代码中,您返回的是图像文件,在javascript中,您必须使用blob作为Text()和JSON()的对比 供进一步阅读
fetch(url, {
method: 'POST',
body: uploadData,
headers: {
'Authorization': 'Bearer ' + this.bearerToken,
}
}).then(res => res.blob()).then((response) => {
if (response) {
const reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
};
reader.readAsDataURL(response);
}
}).catch((error) => {
if (error) {
console.log('Error', error);
this.snackBar.open('Unable to upload image, Try again later!', '', {duration: 4000});
}
});
}
});