Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
How to pass img file to a form

I have an image upload form that makes a post request to a node endpoint /upload. There, my app.js requests a file variable from the form and then (using Multer) pushes that file to a special uploads directory.

<form
        id="form"
        action="/upload"
        method="POST"
        enctype="multipart/form-data"
      >
    // when formBtn is changed (file selected) declare file var and submit
    formBtn.addEventListener("change", function () {
      // file that is requested in app.js
      const file = this.files[0];
      form.submit()
    });

I am trying to add drag and drop functionality. On Body I added <body ondrop="dragHandler(event);"> which calls function dragHandler ondrop and passes in event. Function dragHander() prevents default action (opening image in browser), verifies that what was dropped was a file, defines file, and submits the form.

function dragHandler(event) {
      var file;
      event.preventDefault();
      if (event.dataTransfer.items) {
        if (event.dataTransfer.items[0].kind == "file") {
          file = event.dataTransfer.items[0].getAsFile();
          form.submit;
        } else console.log('not a file');
      }

Because the dropped in file was not uploaded to the form, the post request (made by the form) does not contain the file variable and does not pass that information back to app.js. How would I be able to push my file variable (in dragHandler) into the form so it could be properly transferred to app.js?

app.js:

app.post("/upload", (req, res, next) => {
  upload(req, res, (err) => {
    if (err) {
      console.log("err: " + err);
    } else {
      // req.file is undefined when dropped in
      if (req.file == undefined) {
        console.log("file is not defined");
      } else {
        console.log(req.file);
      }
    }
  });
});
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda