3

I have an input that the user can upload an image, I want to get this image and pass it to the server side and the server will store this image on a local folder, for example:

I use linux for the server so the server.js is running from the folder /home/user/project/server/server.js. When the server get the image I want it to store on the folder /home/user/project/images/img.jpg

This my code:

HTML:

<input type="file" id="imageFile" accept=".jpg, .jpeg, .png" />

Front-End:

const signup = async () => {
  const name = document.getElementById("signup_name").value;
  const passwd = document.getElementById("signup_passwd").value;
  const image = document.getElementById("imageFile").files[0];
  let formData = new FormData();
  formData.append("fileToUpload", image);
  const response = await fetch("http:/localhost:3000/signup", {
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      nome: cadastro_nome,
      senha: cadastro_senha,
      imagem: formData
    }),
  });
  const result = await response.json();
  document.getElementById("cadastro_nome").value = "";
  document.getElementById("cadastro_senha").value = "";
  alert(result);
};

Back-End:

app.post("/signup", async (req, res) => {
  const { name, passwd, image } = req.body;
  if (!name || !passwd) {
    return res.status(400).json("Dados incorretos!");
  }
  knex
    .transaction((trx) => {
      trx
        .insert({
          login: name,
          senha: passwd,
          divida: 0,
        })
        .into("usuarios")
        .then(trx.commit)
        .catch(trx.rollback)
        .then(res.json("Cadastrado com sucesso!"));
    })
    .catch((err) => {
      console.log(err);
      return res.json("Login existente, tente novamente!");
    });
  //PUT SOMETHING HERE TO SAVE IMAGE LOCALLY, MAYBE??
});

Eliabe
  • 33
  • 5
  • Let me confirm. What you want is the user to have a way to download the image he just selected in the input? – Daniel Cruz Oct 31 '22 at 18:23
  • 2
    `fs.write('path/to/image.png', image)` or smth like that depending on exact types I guess – Dimava Oct 31 '22 at 19:04
  • @DanielCruz they used the wrong term, I believe they want the file to be **uploaded** to their **external** server. – ethry Oct 31 '22 at 20:13
  • Sorry for taking too long, @DanielCruz what I want is the user to upload an image, I get this image send to the server and the server store it on a folder locally. Looks like fs.write might be the answer but it gave me an error saying "The 'fd' argument must be of type number. Received type string ('path/to/img', image)" – Eliabe Nov 04 '22 at 14:42
  • Ahhh I understand. So you are trying to save locally in your server the image you get from your view. I had understood locally as from the view. I'll maybe take a look later – Daniel Cruz Nov 04 '22 at 14:49
  • 1
    Yeah, I have a face recognition project, and I want to use the image I get from the user, that's why I want to save it on a specific folder locally. And what I wanna know is the correct way to get this image from the input, send to the back-end(server) and then store it locally on that folder. – Eliabe Nov 04 '22 at 15:02
  • I was investigating and I edited my answer, I hope that information helps @Eliabe – Gonzalo Cugiani Nov 05 '22 at 15:42

1 Answers1

2

Yes, you can first store the uploaded image as a Base64 string using the FileReader, data urls are already base64 so when you call reader.readAsDataURL the e.target.result sent to the reader.onload handler and it will be all you need, but also may need add in your HDD or do it asynchronous using res.json, check the WDN official documentation about FileReader.

(Get user's uploaded image for example)

const imgPath = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();

reader.addEventListener("load", function () {
    // Convert file to base64 string and save to localStorage
    localStorage.setItem("image", reader.result);
}, false);

if (imgPath) {
    reader.readAsDataURL(imgPath);
}

And to read the image back from the localStorage, just use querySelector or getElementById:

const img = document.getElementById('image');
img.src = localStorage.getItem('image');

About the "fd" argument must be of type number, in my case, sometimes I was using:

  • fs.readSync() when I should have been using fs.readFileSync()
  • fs.writeSync() usage but should be fs.writeFileSync()
  • fr.write() could be in your case fs.writeFile()

The comment of @Dimava in your question can work too, I flagged up. For more help, consult this post related to your similar question! ;)

Gonzalo Cugiani
  • 459
  • 2
  • 15