Earlier I was able to upload image from my react app using multi-part form to node server using multer and then created a public_url using cloudinary. But now as I wanted things to be real-time I used socket.io library which is working fine for simple text messages but now I want to include image messages too. So for that I was trying to send the image data from react app (using image picker) and sent to socket-server using socket.emit, I received:
imageData: {
uri: 'file:///storage/emulated/0/Android/data/com.securechat/files/Pictures/68bb637d-a19b-42e6-b083-e697fb429bf4.jpg',
type: 'image/jpeg',
name: 'Thu Jan 06 2022 19:19:27 GMT+0530_displayImage'
}
Now, earlier, when I was using a simple fetch api, it was like:
const upload = require('../utility/multer');
router.post('/register', upload.single('photoURL'), async (req, res, next) => {
const imageResult = await cloudinary.uploader.upload(req.file.path);
})
So, now I was getting the public url of the sent image, imageResult.public_url, then saved this info in mongodb, easy.
But now, as I'm sending through socket, I cannot send it as a multi-part form data from my react app because now I'm just emitting this data like:
Client: socket.emit('listener', {imageData: image});
And this is my socket-server side for receiving this imageData:
socket.on('listener', async data => {
const result = upload.single(data.imageData); // ?????
// now obviously this won't work because multer to be as a middleware & parsing multipart form data...
const imageResult = await cloudinary.uploader.upload(req.file.path); // ?????
io.to(id).emit('new_message', data);
const message = new Message({
id: generateRandomId(),
image: data.imageResult.public_url, // NEED TO CONVERT IT TO STRING OF CLOUDINARY SOMEHOW
});
await message.save();
});
So, as you can see my problem, is there any way to achieve this using multer, I just need a way to get the file path and upload it to cloudinary & then finally get the .public_url so that I could save the message in my db.
In short:
I sent image data from client (react-native) as: socket.emit('listener', {imageData: image});
I received the below data in my socket-server:
imageData: {
uri: 'file:///storage/emulated/0/Android/data/com.securechat/files/Pictures/68bb637d-a19b-42e6-b083-e697fb429bf4.jpg',
type: 'image/jpeg',
name: 'Thu Jan 06 2022 19:19:27 GMT+0530_displayImage'
}
I just need a way to get a req.file.path like multer generates when sent as multi-part formData (but now I'm emitting using socket.io), and then save it to cloudinary to get a public_url.