如何使用react-camera将jpg图像发送到服务器?

时间:2018-09-12 05:55:53

标签: javascript node.js reactjs amazon-s3 npm

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

我测试时,lambda函数似乎可以正常工作,但是我无法弄清楚到底需要从React Camera发送什么。
或者,如果我通过正确的格式发送以上传它。

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时使用正确的图像格式?

1 个答案:

答案 0 :(得分:1)

组织得很好的问题和代码...谢谢!

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

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));
    })
}
相关问题