前言:
最近在公司推荐研发任务时实现了拍照识别功能,需要调起系统相机,笔者实现之后,将实现的流程分享给各位小伙伴
功能描述:
点击相机icon调起系统相机,同时可以选择是拍摄还是使用相册图片,然后传递给后端,后端处理之后,前端获取结果并进行展示
具体代码实现:
import React, {
useState,
useRef,
} from "react";
const PhotoResult = (props) => {
const fileInputRef = useRef(null);
const [imagePreview, setImagePreview] = useState("");
const [searchPhotoResuilt, setSearchPhotoResuilt] = useState({});
const handleImageClick = () => {
fileInputRef.current.click(); // 触发input点击
};
const handleFileChange = (e) => {
const file = e.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = (e) => {
setImagePreview(e.target.result);
};
reader.readAsDataURL(file);
// 上传到后端
uploadImage(file);
};
const uploadImage = async (file) => {
const formData = new FormData();
formData.append("file", file); // key 需和后端一致
try {
$postMiniImage(
`你的请求名`,
formData,
token
).then((res) => {
if (res.code === 200) {
setSearchPhotoResuilt(res.data);
}
});
} catch (error) {
console.error("上传失败:", error);
}
};
return (
<>
<img className="photo-img" onClick={handleImageClick}/>
<input
type="file"
accept="image/*"
//只调起相机
//capture="camera"
ref={fileInputRef}
onChange={handleFileChange}
//取消选取图片执行的操作
onCancel={() => {
router.back();
}}
className="hidden-input"
/>
</div>
</>
);
}
//重要将input框进行隐藏
.hidden-input {
display: none;
}