前端
1. 下载 Webcam 实现调用摄像头功能
import Webcam from 'react-webcam';
2. 调用摄像头进行拍照
<div className="camera">
<Webcam
audio={false}
ref={webcamRef}
style={{
width: '100%',
}}
/>
<Button block color="primary" size="large" onClick={captureImage}>
拍照并上传
</Button>
</div>
3. 处理拍出来的图片并进行格式处理
const captureImage = () => {
const imageSrc = webcamRef.current.getScreenshot();
// 将图像数据发送到服务器
uploadPic(imageSrc);
};
//将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' },
};
const resp = await axios.post('http://localhost:3000/uploadImg', fd,config)
let img = resp.data.path
let info = { id: user._id, img }
let { data } = await axios.post('http://localhost:3000/eduserimg', info)
if (data.code === 200) {
Toast.success(data.msg)
localStorage.setItem('user', JSON.stringify(data.newuser))
setIstrue(false)
setShow(false)
}
};
后端
后端处理,可以通过以下链接中的后端操作进行查看
更改头像https://blog.csdn.net/Aan___/article/details/134610262?spm=1001.2014.3001.5502