0

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.

Molda
  • 5,619
  • 2
  • 23
  • 39
Nadeem
  • 145
  • 1
  • 13
  • 1
    If this is a Node server communicating with a browser, there's probably no need to use `mv`, just [write the DataURL to disk](https://stackoverflow.com/a/20272545/726766) using the native `fs` module. – shennan Nov 05 '17 at 08:05
  • yes @shennan but mv is easier a bit – Nadeem Nov 05 '17 at 08:08
  • [mv](https://www.npmjs.com/package/mv) writes files, not DataURL's. So in this case it's not easier. It's the wrong tool for the wrong job. – shennan Nov 05 '17 at 08:10
  • so fs is a good tool for it ! @shennan – Nadeem Nov 05 '17 at 08:16
  • 1
    `fs` can write buffers to disk, and as I said in my previous comment; [this answer](https://stackoverflow.com/a/20272545/726766) shows you how to convert a DataURL image into a buffer. – shennan Nov 05 '17 at 08:19

0 Answers0