首页 > 解决方案 > 如何使用 react-camera 将 jpg 图像发送到服务器?

问题描述

我的目标是将从网络摄像头拍摄的图像上传到 Lambda 函数,然后将其上传到 AWS S3。

lambda 函数在我测试时似乎可以工作,但是我无法确定需要从 React 相机发送什么。
或者,如果我通过正确的格式发送来上传它。

import Camera from 'react-camera';

..
这是 JSX

<Camera
  ref={(cam) => {
    this.camera = cam;
  }}
>
  <Button onClick={this.takePicture}>
    <i className="fas fa-camera"></i> &nbsp; Take photo
  </Button>
</Camera>

这是他们拍照时调用的反应代码

takePicture = () => {
  this.camera.capture()
    .then(blob => {
      console.log(blob);
      this.props.dispatch(uploadImage(blob))
    })
}

我的操作中的 uploadImage 函数是:

export const uploadImage = (fileObj) => dispatch => {

  return fetch(url, {
    method: 'POST',
    headers: {
      'Accept': 'image/jpeg'
    },
    body: fileObj
  })
    .then((response) => response.json())
    .then(function (response) {
      if (response.status === 'success') {
        console.log(response);
        // ... Show feedback
        return response
      } else {
        // ... Show feedback
      }
    })
    .catch((error) => {
      console.error(error)
    });
}

我想我需要上传一个base64图像..?我不明白我是如何从blob


以下是供参考的 Lambda 函数代码:

  var params = { 
    Bucket: 'bucketName', 
    Key: Date.now() + '.jpg',
    ContentType: 'image/jpeg',
    Body: event.body,
    ACL: "public-read"
  };
  return uploading = new Promise(function (resolve, reject) {
    return s3.upload(params, function (err, data) {
      if(err) {
        state.uploadError = err
        return reject({
          error: err,
          status: 'error',
          message: 'something went wrong'
        })
      }
      state.uploadData = data
      state.fileLocation = data.Location
      state.status = "success"
      state.message = "File has been uploaded to the fileLocation"
      return resolve(data)
    });
  })

问题:

如何使格式blob正确,以便在POST编辑时body成为正确的图像格式?

标签: javascriptnode.jsreactjsamazon-s3npm

解决方案


非常有条理的问题和代码......谢谢!

更新:
使用文件系统模块读取文件并指定编码。

const fs = require('fs');

takePicture = () => {
  this.camera.capture()
    .then(blob => {
      console.log(blob);
      const image = fs.readFileSync(blob.path);
      const b64Image = Buffer.from(image).toString('base64');
      this.props.dispatch(uploadImage(b64image));
    })
}

推荐阅读