简体   繁体   English

正确渲染图像 Blob

[英]Rendering Image Blob Correctly

I'm trying to render an <img> from a blob.我正在尝试从 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;

The output of the first console.log() is something like:第一个console.log()的输出类似于:

Blob(5842218) {size: 5842218, type: "application/json"}

I think the type might be why it's not rendering, but I'm not sure.我认为type可能是它不渲染的原因,但我不确定。

The output of the second console.log() is something like:第二个console.log()的输出类似于:

blob:http://localhost:3000/12bfba06-388d-48e2-8281-5ada40a662de

The getImageBlob() function is: getImageBlob()函数是:

export const getImageBlob = () => new Promise((res, rej) => {
  client
    .get(`${IMAGES}`, {
      responseType: 'blob',
    })
    .then((resp) => {
      res(resp.data);
    })
    .catch((err) => {
      rej(Error(err.message));
    });
});

It's possible the server is sending back something incorrectly, so I can post that code if necessary.服务器可能会错误地发回某些内容,因此我可以在必要时发布该代码。

updated with server code使用服务器代码更新

This is the code which sends back the image blob.这是发回图像 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);
      }
    });
  });
};

Output of console.log() on server side:服务器端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(5842218) {size: 5842218, type: "application/json"}Blob(5842218) {size: 5842218, type: "image/jpeg"}更改类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM