javascript - 如何使用 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> 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
成为正确的图像格式?
解决方案
非常有条理的问题和代码......谢谢!
更新:
使用文件系统模块读取文件并指定编码。
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));
})
}
推荐阅读
- angular - 如何在子组件中使用 formGroupName
- python - 如何在嵌套的numpy数组中用一行“NaN”替换带有浮点值的行?
- c++ - 在 C++ 多态中,如何避免函数的名称隐藏(调用错误没有匹配的函数)?
- laravel - 在 laravel 中进行测试的模拟卷曲响应
- generics - 如何将类型传递给 Kotlin 中的泛型方法?
- c++ - 如何从 Boost 库中理解这段 C++ 代码?
- android - 未从另一个意图过滤器调用“onCreate()”方法
- linux - Curl 以 ASCII 格式下载 tar.gz 文件
- javascript - 在 findOneAndUpdate Mongoose 5.x 之后从数组中检索特定记录
- pandas - Pandas 按排名的条件累积总和