I have made a chat application in node JS and JavaScript. I am giving user a free hand to upload their picture for profile.
I am using Node JS mv
module and trying to move or copy a file user select, to my specific directory. I am using Socket.io
to communicate with node.
The problem is, I am using an input[type=file]
when a user select an image file, I get the value
of this image file.
This is what I get in return: C:\fakepath\image.png
.
When I pass it to the mv
method, it throw an error: No such directory
, because of the fakepath
. I tried to get the real path of my file to pass it to the mv
method, so that it can move the file to the directory I want. I tried using FileReader()
and then invoked fr.readAsDataURL(file);
and it returns the below text :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAMAA...... // shortened
This is my Javascript
var file_inp = document.getElementById("upl_img");
file_inp.addEventListener("change",(e)=>{
if('files' in file_inp){
if(file_inp.files.length==0){
alert("Select an Image to upload !");
}else{
var file = file_inp.files[0];
var fr = new FileReader();
console.log(file_inp.value);
if(file){
fr.readAsDataURL(file);
}
fr.onloadend = ()=>{
console.log(fr.result)
socket.emit("upload_image",{path:fr.result,name:file_inp.files[0].name,size:file_inp.files[0].size})
}
}
}
})
This is the node script
socket.on("upload_image",(data)=>{
mv(data.path, './user_images', function(err) {
if(err) throw err;
console.log('File Moved ! ')
});
})
Note: I only need to move the file to the user_images
directory, when the user select a picture.