响应中的 Blob() 不显示原始图像 url,而是显示大小和类型

Blob() in a response isn't displaying original image url but size and type

虽然我没有遇到任何错误,但我没有显示图像,因为它在 POSTMAN 上完美显示。我使用了 res.json(),我收到了 "unexpected token < in position 0"。然后我尝试了 res.text() 并且我可以使用 res.blob() 但是当我将它与 url = URL.createObjectURL(blob) 一起使用时。我得到了一个不同的文件名,无法从 API 中检索用于显示。 我知道有几个关于堆栈溢出的参考资料,但与我打算做的不同,而且随着我尝试这么多选项,它变得越来越复杂。

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,

这是return的回应; return

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});
              }
            });
          }
        });

进一步阅读...

enter link description here