我正在尝试将 FormData 从 React-Native 应用程序发送到 Express(打字稿中的所有内容)后端。然而,我所做的一切似乎都不起作用。
客户端:
const handlePickImage = async () => {
try {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
if (!result.canceled) {
const uri = result.assets[0].uri;
setProfileImage(uri);
const formData = new FormData();
const fileName = uri.split('/').pop();
const response = await fetch(uri);
const blob = await response.blob();
formData.append('profileImage', blob, fileName || 'profile_image.jpg');
await updateProfilePicture(formData, user.uid);
}
} catch (error) {
console.error('Error picking image:', error);
}
};
前端API:
export const updateProfilePicture = async (profilePicture: FormData, userId: string) => {
try {
console.log("Profile picture: ", profilePicture)
const response = await fetch(`${API_URL}/user/updateprofilepicture/${userId}`, {
method: 'POST',
headers: {
Accept: 'application/json',
},
body: profilePicture,
});
if (!response.ok) {
throw new Error('Failed to update profile picture');
}
const data = await response.json();
console.log('Profile image uploaded successfully:', data);
} catch (error) {
console.error('Error updating profile picture:', error);
}
};
后端路由:
const multer = require('multer');
const express = require('express');
const router = express.Router();
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
router.post('/updateprofilepicture/:userId', upload.single('profileImage'), updateProfilePicture);
控制器:
import { Multer } from 'multer';
export const updateProfilePicture = async (req: Request, res: Response) => {
try {
const userId = req.params.userId;
const file = req.file;
if (!file) {
return res.status(400).json({ error: 'No file uploaded' });
}
const imageUrl = await uploadProfileImage(userId, file);
res.status(200).json({ imageUrl });
} catch (error) {
console.error('Error in updateProfilePicture controller:', error);
res.status(500).json({ error: 'Error uploading profile picture' });
}
};
我错过了一些简单的事情吗?我可以毫无问题地在前端 api 中记录数据,但无法将数据发送到控制器并获取任何内容。
谢谢你
我有过几次这样的经历,其中有几次,有效的方法是更新标题。你可以尝试像这样使用 multipart/form-data
export const updateProfilePicture = async (profilePicture: FormData, userId: string) => {
try {
console.log("Profile picture: ", profilePicture)
const response = await fetch(`${API_URL}/user/updateprofilepicture/${userId}`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: profilePicture,
});
if (!response.ok) {
throw new Error('Failed to update profile picture');
}
const data = await response.json();
console.log('Profile image uploaded successfully:', data);
} catch (error) {
console.error('Error updating profile picture:', error);
}
};