Using Multer to parse FormData on my Node backend always results in req.file being undefined. Sending the data from my frontend RN code to my backend EC2 server using fetch.
RN Frontend
const pickImage = async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
if (!result.canceled && result.assets.length > 0) {
const asset = result.assets[0];
const form = new FormData();
form.append("file", {
uri: asset.uri,
name: asset.fileName,
type: asset.mimeType,
} as any);
setFormData(form);
}
};
const uploadNewProfileImage = async () => {
...
const response = await fetch(`${BACKEND_URL}/upload-profile-image`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
body: formData
});
...
}
Node Backend
const storage = multer.memoryStorage();
const upload = multer({
storage: storage,
limits: {
fileSize: 20 * 1024 * 1024,
}
});
router.post('/upload-profile-image', upload.single('file'), async (req, res) => {
const file = req.file;
// Send to S3 bucket
}
I think the browser is properly sending the request:
Content-Disposition: form-data; name="newimage"
I've tried with Content-Type headers. I've tried Multer with DiskStorage instead of Memory. I've tried the answer from here. I've made sure Nginx will accept 20MB files. I've verified the uploads/ folder exists in the same folder as my node file. Not sure what else I can try to have multer parse the formdata into a usable format to upload to AWS S3.
You can't manually set only three properties for the FormData variable.
const asset = result.assets[0].file;
const form = new FormData();
form.append("newimage", asset as any);
Using the whole file fixes the issue.