node.js - 如何在 react 和 node.js 中将数据从客户端发送到服务器?
问题描述
我正在尝试制作一个功能,让用户从前端上传他们的个人资料图像并将图像发送回服务器。我该怎么做?
我正在使用 multer 来执行此功能。
这是我来自服务器路由的代码库:
router.post('/upload', upload.single('upload'), async (req, res) => {
try {
const incident = await incident.findById(req.body.id);
incident.image = req.file.buffer;
incident.save();
res.send();
} catch (e) {
res.status(400).send(e);
}
}, (error, req, res, next) => {
res.status(400).send({ error: error.message });
});
这是我前端的 UserProfile.js:
const UserProfile = (serverUserData) => {
const appState = useContext(GlobalContext);
const { currentUser } = appState;
const { email, picture, name } = currentUser;
const [isVerified, setIsVerified] = useState(false);
const checkVerificationData = () => {
axios.get("/api/v1/profiles/profile").then((res) => {
const { data } = res;
if (data.verifiedDT) {
setIsVerified(data.verifiedDT);
}
});
};
useEffect(() => {
checkVerificationData();
}, [isVerified]);
// Upload user avatar function
const [imageSelected, setImageSelected] = useState("");
const uploadImage = () => {
const formData = new FormData();
formData.append("file", imageSelected);
formData.append("upload_preset", "teammateme");
axios.post("http://localhost:8080/upload/", formData)
.then((response) => {
if (response.status === 200) {
checkVerificationData();
currentUser.picture = response.data.url;
}
});
};
这是出现用户个人资料图像的 UserCard.js:
{picture ? (
<div>
<Avatar
src={picture}
alt="Avatar"
className="avatar--profile_image"
/>
<input
type="file"
onChange={(event) => {
onSelectedImage(event.target.files[0]);
}}
/>
<button onClick={uploadImage}>Submit</button>
</div>
) : (
<AccountCircleIcon className="avatar--profile_image" />
)}
解决方案
推荐阅读
- c - 我想将 4 个字符串作为输入并显示到另一个数组中
- python - Python 处理配置的最佳方式
- python - 图像旋转后如何计算新点的位置
- javascript - NodeJs & Express Learning RESTFUL,在提交要更新的表单时,它会创建一个带有新 ._id 的新表单,而不是更新原始表单
- spring - Bazel 运行与测试
- python - 检查嵌套列表中的所有元素在python中是正数还是负数
- r - 如何在树莓派(RaspbianOS)上安装 RStudio
- ruby-on-rails - 如何使用操作电缆向 Rails 中的单个用户发送通知
- css - 材质 UI 弹出框 - 小屏幕上的位置
- python - Python - 以 10 为底的 int() 的无效文字:'\ufeeff0'