调用摄像头拍照并保存到后端数据库(最新)
【代码】调用摄像头拍照并保存到后端数据库。
·
下载插件
使用npm:
npm i react-webcam使用yarn:
yarn add react-webcam
使用npm:
npm i react-webcam
使用yarn:
yarn add react-webcam
前端
import React, { useEffect, useRef, useState } from 'react';
import Webcam from 'react-webcam';
import axios from 'axios';
import { history } from 'umi';
import './index.less';
import { Button } from 'antd-mobile';
export default function CameraComponent() {
const webcamRef = useRef(null);
const [obj, setObj] = useState(
JSON.parse(window.sessionStorage.getItem('userinfo')),
);
const captureImage = () => {
const imageSrc = webcamRef.current.getScreenshot();
// 将图像数据发送到服务器
uploadPic(imageSrc);
history.push('/');
};
//将base64格式的图片转换成formdata格式,并上传到后台并获取本地图像
const uploadPic = async (base64String) => {
// 下面将要把 base64 转换成formdata
// 这里对base64串进行操作,去掉url头,并转换为byte
let bytes = window.atob(base64String.split(',')[1]);
let array = [];
for (let i = 0; i < bytes.length; i++) {
array.push(bytes.charCodeAt(i));
}
let blob = new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
// 生成FormData对象
let fd = new FormData();
// 注:此处 file 应和后台接收参数匹配
fd.append('file', blob, Date.now() + '.jpg');
let config = {
headers: { 'Content-Type': 'multipart/form-data' },
};
let { data } = await axios.post(
'http://localhost:3000/img',
fd,
config,
);
console.log(data);
obj[0].image = data.path;
window.sessionStorage.setItem('userinfo', JSON.stringify(obj));
};
return (
<div className="camera">
<Webcam
audio={false}
ref={webcamRef}
style={{
width: '100%',
}}
/>
<Button block color="primary" size="large" onClick={captureImage}>
拍照并上传
</Button>
</div>
);
}
后端
创建一个upload用来接收照片
router.post("/img", async (req, res) => {
let form = new multiparty.Form()
form.uploadDir = "upload"
form.parse(req, (err, formData, imgData) => {
console.log(imgData);
res.send({ path: "http://localhost:3000/" + imgData.file[0].path })
})
})
更多推荐
已为社区贡献1条内容
所有评论(0)