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

标签 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>

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

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 Function 代码供引用:

  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的格式正确,以便当它作为body进行POST编辑时,它将是正确的图像格式?

最佳答案

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

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

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));
    })
}

关于javascript - 如何使用react-camera将jpg图像发送到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52288332/

相关文章:

javascript - 使用 Express 上的 API key + Secret 保护我的 RESTful API

javascript - 如何使用nodemailer发送pdf附件?

node.js - 无法解析模块 `react/lib/ReactComponentTreeHook`

reactjs - react : how to navigation without refresh page using office UI fabric

javascript - 退出全屏模式时捕获 ESC 事件

Javascript 未检测到数组中的数字 79 或 16

php - 使用 https 确保 html 表单安全

javascript - 如何将日期转换为 HTML 中的单词

javascript - 如何在 mixins 上的扩展/继承情况下正确定义 Node.js 模块的 JSDoc

reactjs - 使用 Enzyme 和 Jest 测试 React 组件中包含的文本