Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
upload image to node js server + javascript and display in the same page with ajax jquery

I need to upload a image(jpg||png||jpeg) to the server I created with node js.

I have the router and the requestHandlers.. that redirect to this function:

  function reqUpload(request, response) {
    var form = new formidable.IncomingForm();
    form.parse(request, function (error, fields, files) {
        lastFileUploaded=files.up.originalFilename;
        if (files.up.originalFilename.match(/\.(jpg|jpeg|png)$/i)) {
            //check if alredy exists
            fs.access(files.up.originalFilename, fs.F_OK, (err) => {
                if (err) {
                    fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
                        if (err) {
                            fs.unlink(files.up.originalFilename);
                            fs.rename(files.up.filepath, files.up.originalFilename);
                        }

                        var data;
                        fs.readFile('./html/std.html', 'utf8', function (err, data) {
                            if (err) {
                                console.error(err);
                                return
                            }
                            response.writeHead(200, { "Content-Type": "text/html" });
                            response.write(data);
                            response.end();
                            
                        });
                    })
                }else{
                    console.log("Already exists, replacing it!");
                    fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
                        if (err) {
                            fs.unlink(files.up.originalFilename);
                            fs.rename(files.up.filepath, files.up.originalFilename);
                        }
                })}

            });
        } else {
            console.log("format not accepted! try again.");

        }

This is working if I upload my file via a button and the form action ="/reqUpload" however, I need to load in the same page.

How do I do it with ajax + jquery?

I need to display the image uploaded in the same page I uploaded it, without refreshing the page.

I have this function:

function loadPhoto(e){

alert("entered")   
var xhr = new XMLHttpRequest();
xhr.open('POST', '/reqUpload');
xhr.onload = function(){
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    alert(this.responseText)
         document.getElementById('#photo').innerHTML = this.responseText;
}
xhr.send('/html/std.html');
e.preventDefault();

}

but it breaks and returns this: enter image description here

seems not to send the file in the correct format, or smth like that

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This resolved my case

function loadPhoto(e){
e.preventDefault();
//forming images
var formData  = new FormData( document.getElementById("uploading") );
for(var i = 0; i < document.getElementById("up").files.length; i++) {
  console.log(i)
  formData.append("up[]",document.getElementById("up").files[i]);
}


var filename = document.getElementById('up');
alert(filename)
filename = filename.files[0].name;
alert(filename)

var xhr = new XMLHttpRequest();
xhr.open('POST', '/reqUpload');
xhr.onload = function(){
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    alert(this.responseText)
         document.getElementById('#photo').innerHTML = this.responseText;
}
xhr.send(formData);

}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda