Eliabe
Eliabe

Reputation: 33

How do I save an image locally with HTML and JS?

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??
});

Upvotes: 3

Views: 4309

Answers (1)

Gonzalo Cugiani
Gonzalo Cugiani

Reputation: 650

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! ;)

Upvotes: 2

Related Questions