javascript - 正确渲染图像 Blob

标签 javascript html node.js reactjs

我正在尝试渲染 <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(5842218) {size: 5842218, type: "application/json"}Blob(5842218) {size: 5842218, type: "image/jpeg"}改变类型

关于javascript - 正确渲染图像 Blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911646/

相关文章:

javascript - 函数不在 angularjs 文件中运行

javascript - 使用javascript加载页面时如何将光标置于文本框中?

javascript - Jquery Onclick 文本到文本字段

c# - 无法设置状态代码

javascript - 函数不会更新变量

json - 将手写笔存储在 JSON/文档数据库中

javascript - 在哪里引用 Ionic 的 template/[xxx].html 的 JavaScript 文件

html - 如何在另一个下方创建两个响应单元格?

node.js - 如何在我的 Express route 允许使用斜线?

javascript - Node.js puppeteer - 在循环中使用数组中的值来循环浏览页面