【问题标题】:Unable to display image reactjs无法显示图像reactjs
【发布时间】:2018-10-14 21:43:22
【问题描述】:

我使用邮递员为我创建的 API 保存了一张图片。 图片的保存方式是:

const newProduct = new Product({
    name: req.body.name,
    referenceId: createReferenceId(),
    category: req.body.category,
    image: {
      data: fs.readFileSync(req.body.image),
      contentType: "image/jpg"
    },
    metadata: req.body.metadata
  });
  newProduct
    .save()
    .then(product => res.json(product))
    .catch(err => res.json(err));

我的猫鼬模式如下所示:

const ProductSchema = new Schema({
 name: { type: String, required: true },
  referenceId: { type: String, required: true },
  category: { type: String, required: true },
  image: { contentType: String, data: Buffer },
  metadata: { type: String }
});

我存储的数据如下所示:

[255, 216, 255, 224, 0, 16, 74, 70, 73, 70, 0, 1, 2, 1, 0, 100, 0, 100, 0, 0, 255, 225, 13, 5, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 7, 1, 18, 0, 3, 0, 0, 0, 1, 0, 1, 0, 0, 1, 26, 0, 5, 0, 0, 0, 1, 0, 0, 0, 98, 1, 27, 0, 5, 0, 0, 0, 1, 0, 0, 0, 106, 1, 40, 0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1, 49, 0, 2, 0, 0, 0, 20, 0, 0, 0, 11]

我想在 reactJS 中显示这个保存的图像?我很困惑我怎么能这样做。请帮忙。

【问题讨论】:

    标签: javascript node.js reactjs react-native react-redux


    【解决方案1】:

    您可以将图像保存为 dataURL。以下是我为了从 dropzone 组件中提取图像数据而创建的承诺。

    const promise = new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(filesToUpload[0]);
        reader.onload = () => {
          if (reader.result) {
            resolve(reader.result);
          } else {
            reject(Error('Failed converting to base64'));
          }
        };
    });
    

    然后您可以使用 promise 中的then() 方法访问数据。

    promise.then((result) => {
      // This is the result
      console.log(result);
    }, (err) => {
      console.log(err);
    });
    

    一旦您检索到 dataURL,请将其发布到您的 API。然后就可以很方便的使用<img>中的src属性来显示图片了。

    希望这会有所帮助。干杯!

    【讨论】:

      【解决方案2】:

      将数组缓冲区转换为 base64 并在您的 html 部分中使用该变量。

      let arrayBuffer = "Your data from api";
      
      var base64Val = window.btoa(
                       new Uint8Array(arrayBuffer).reduce((data, byte) => 
                          data + String.fromCharCode(byte), ''
                       )
                   );
      
      <img src={`data:image/jpeg;base64,${base64Val}`} />
      

      【讨论】:

        猜你喜欢
        • 2021-03-04
        • 1970-01-01
        • 2019-01-05
        • 2018-01-27
        • 1970-01-01
        • 2022-06-28
        • 2013-12-31
        相关资源
        最近更新 更多