I am selecting an Image from FileManager and getting a result, added below to refer. I am passing that data to nodejs but getting data in array of array format. I am passing Image with data in FormData. I am sucessfully sending data to nodejs but i am getting issue to upload the image in destination folder. I am new to React Native. Can anyone help me out yrr.
Logged Data on Image Seleting :
Object {
"cancelled": false,
"height": 960,
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%40anonymous%2FLevelNextClient-d47662dc-9f84-4299-a322-f00845340c43/ImagePicker/1f5613bd-72ee-4ba3-8b9b-1456fe05bfb3.jpg",
"width": 960,
}
Logged Data when getting in req.body :
[["name","Anujw5rc"],["email","[email protected]"],["phone","333333"],["image",{"uri":"file:///data/user/0/host.exp.exponent/cache/ExperienceData/%40anonymous%2FLevelNextClient-d47662dc-9f84-4299-a322-f00845340c43/ImagePicker/55c1a503-da15-47bb-adcb-2005cfc66b82.jpg","name":"UserProfile.jpg","type":"image/jpg"}]]
const handleUpdate = async ({ name, email, phone }) => {
const data = new FormData();
let str=image.replace('///','//')
data.append('name', name)
data.append('email', email)
data.append('phone', phone)
data.append('image',
{
uri:image,
name: "UserProfile.jpg",
type:'image/jpg'
});
const response = await axios.post(`${ConfigData.SERVER_URL}/auth/updateProfile`,
data,
);
if (response.status !== 200) throw Error('Something went wrong')
if (response.data.status === false) throw Error(response.data.message)
}
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [3, 3],
quality: 1,
// base64: true,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
}
};
router.post("/updateProfile", fileUpload.array("file"), async (req, res) => {
console.log(JSON.stringify(req.body._parts));
console.log(req.file);
const user_id = req.body.id;
try {
const updateData=await userModel.findByIdAndUpdate(user_id,
{ name: req.body.name, email: req.body.email ,number: req.body.number,ProfileImageDestination : req.body.image},
);
res.status(200).json({ status: true ,updateData});
} catch (e) {
console.log(e);
res.status(500).json({ status: false, message: "Something Went Wrong" });
}
});
CodePudding user response:
in the react native part, you not need to replace image uri using
let str=image.replace('///','//')
in handleUpdate method. You can directly pass in Formdata to the backend API like
data.append('file',
{
uri:image,
name: "UserProfile.jpg",
type:'image/jpg'
});
where image is your state variable that stored the image.uri of Picked image.
And then, in the backend API you may have two choices either busboy or multer for fileupload.
Using busboy,
var Busboy = require('busboy'),
path = require('path'),
fs = require('fs');
router.post("/updateProfile", async (req, res) => {
var busboy = new Busboy({ headers: req.headers });
var saveLocation = '';
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
saveLocation = path.join(__dirname, 'uploads/' filename);
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', function() {
(async ()=>{
const user_id = req.body.id;
try {
const updateData=await userModel.findByIdAndUpdate(user_id,
{ name: req.body.name, email: req.body.email ,number: req.body.number,ProfileImageDestination : req.body.image},
);
res.writeHead(200, { 'Connection': 'close' });
res.end({ status: true ,updateData});
} catch (e) {
console.log(e);
res.writeHead(200, { 'Connection': 'close' });
res.end({ status: false, message: "Something Went Wrong" });
}
})()
});
return req.pipe(busboy);
});
Above code is for just demonstration purpose, you can find out more details to use busboy on library https://www.npmjs.com/package/busboy.
Another alternative is multer you can explore for the file upload to the specific directory or location at server side.