正确渲染图像Blob

6
我正在尝试从 Blob 中渲染 <img> 图像。
import React from 'react';
import { getImageBlob } from '../api/images';

class ImageViewer extends React.Component {
   state = {
     src: undefined,
     loading: true,
   }

  componentDidMount() {
    getImageBlob()
      .then((imageBlob) => {
        console.log(imageBlob);
        const urlCreator = window.URL || window.webkitURL;
        const imageUrl = urlCreator.createObjectURL(imageBlob);
        console.log(imageUrl);
        this.setState({ src: imageUrl, loading: false });
      })
      .catch((err) => {
        console.error(err);
        this.setState({ loading: false });
      });
  }

  render() {
    if (this.state.loading) {
      return 'loading';
    }

    return <img src={this.state.src} height={100} width={100} />;
  }
}


export default ImageViewer;

第一个console.log()的输出大致如下:
Blob(5842218) {size: 5842218, type: "application/json"}

我认为可能是type的原因导致它没有渲染,但我不确定。

第二个console.log()的输出大致如下:

blob:http://localhost:3000/12bfba06-388d-48e2-8281-5ada40a662de
getImageBlob()函数是:
获取图像二进制数据的函数。
export const getImageBlob = () => new Promise((res, rej) => {
  client
    .get(`${IMAGES}`, {
      responseType: 'blob',
    })
    .then((resp) => {
      res(resp.data);
    })
    .catch((err) => {
      rej(Error(err.message));
    });
});

可能是服务器发送的数据有误,如果需要,我可以发布代码。

更新服务器代码

以下是将图像Blob返回的代码。

const getImage = (imageKey) => {
  const params = {
    Bucket: process.env.S3_BUCKET,
    Key: imageKey,
  };

  return new Promise((res, rej) => {
    s3.getObject(params, (err, data) => {
      if (err) {
        rej(Error(err.message));
      } else {
        console.log(data);
        res(data);
      }
    });
  });
};

console.log() 在服务器端的输出结果:

{ AcceptRanges: 'bytes',
  LastModified: 2018-08-18T18:07:39.000Z,
  ContentLength: 2101981,
  ETag: '"be594978d48fdc5964eb97ffb2c589f1"',
  ContentEncoding: 'blob',
  ContentType: 'image/jpg',
  Metadata: {},
  Body:
   <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 27 10 00 00 27 10 08 06 00 00 00 ba 4e 62 27 00 00 20 00 49 44 41 54 78 5e ec d0 01 0d 00 30 08 ... > }

问题出在你的内容类型上。从 blob 的大小可以看出服务器已经做好了它的部分,只是你的客户端出现了问题。我相信这个重复的解决方案可以解决提供图像的问题。 - Travis J
getImageBlob() 中的 contentType 设置为 image/jpeg 似乎不起作用。应该将其设置为 application/json 吗? - Colin Ricardo
自从问题发布以来,我一直在努力解决它,但似乎无法从您发布的问题中解析出可行的解决方案——特别是您提到服务器似乎已经正确返回数据。我会更新服务器代码以防万一。 - Colin Ricardo
@Rubelhasan 在你删除回答之前我已经尝试过了,但它仍然不起作用,现在 Blob 对象的大小只有 2 - Colin Ricardo
你好,您在前端代码中移除了以下的代码吗?console.log(imageBlob); const urlCreator = window.URL || window.webkitURL; const imageUrl = urlCreator.createObjectURL(imageBlob); console.log(imageUrl);谢谢。 - Rubel hasan
显示剩余9条评论
1个回答

0

我觉得应该改变类型,而不是将Blob(5842218) {size: 5842218, type: "application/json"}改为Blob(5842218) {size: 5842218, type: "image/jpeg"}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接