upload an image in html and javascript

1

I am sending an image to my web server that I select from my HTML in the following way:

<form method="POST" action="http://'+ip+'/HelloSpringMVC/uploadFile" action="subirFoto();" enctype="multipart/form-data">
   File to upload: <input type="file" name="file"><br/>
   <input type="submit" value="Upload"> Press here to upload the file!
</form>

My problem is that doing this in addition to doing the POST with the image to my web server redirects me the page to that address thing that I do not want to happen, I want to keep it in the HTML it is in, ¿ How could I solve it?

I would also like to know if this can be done in Javascript

    
asked by Silvia 14.05.2018 в 20:46
source

3 answers

1

Use formData to upload file.

HTML :

<input type="file" id="filechooser">

Javascript :

function uploadFile() {
    var blobFile = $('#filechooser').files[0];
    var formData = new FormData();
    formData.append("fileToUpload", blobFile);

    $.ajax({
       url: "upload.php",
       type: "POST",
       data: formData,
       processData: false,
       contentType: false,
       success: function(response) {
           // .. hacer algo...
       },
       error: function(jqXHR, textStatus, errorMessage) {
           console.log(errorMessage); // Opcional
       }
    });
}

See browser support: link

  

SO Source:

     

Another example is found here:

     

Another example:

function mostrar(){
  var archivo = document.getElementById("file").files[0];
  var reader = new FileReader();
  if (file) {
    reader.readAsDataURL(archivo );
    reader.onloadend = function () {
      document.getElementById("img").src = reader.result;
    }
  }
}
<input type="file" id="file" accept="image/*" onchange="mostrar()"/>
<br>
<img id="img"/>
    
answered by 14.05.2018 в 21:10
0
var formulario = $('#subirFoto'); //Donde el el selector subirFoto debe estar dentro de la etiqueta form como id es decir <form id="subirFoto" enctype="multipart/form-data">

formulario.submit(function( event ) {
event.preventDefault();
$data = $formulario.serialize();

    $.ajax({
        beforeSend: function () {
              //que quieres hacer antes de enviar la información
        }
        type: 'POST',
        url: 'subirFoto.php',//Ruta donde va a ser enviado el formulario
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {

               //Response devuelve una respuesta del archivo subirFoto.php
               //Puede ser un json que es lo mas común utilizar en estos casos
        },
        error: function (response) {
               //En caso de que suceda algún error con el envío de información
        }
    });
});
    
answered by 14.05.2018 в 21:19
0

OK you first have to use an event in ajax to save the image and do not rename the page and use a jquery file upload event to upload the image, in my case I use jquery fileupload here is the information

here's your view

 <form method="POST" action="" enctype="multipart/form-data">
            File to upload: <input type="file" name="file"><br/>
            <input type="button" id="button" value="Upload"> Press here to upload the file!
        </form>

al input del submit lo cambiamos a button

y el jquery es 

$("#button").on("click",function(){
        var url = window.location.hostname === 'url';
        $('#fileupload').fileupload({
            url: url,
            dataType: 'json',
            done: function (e, data) {
                $.each(data.result.files, function (index, file) {
                    $('<p/>').text(file.name).appendTo('#files');
                });
            }

        })
    });  

in the same way here I leave the link of the fileupload link

    
answered by 14.05.2018 в 21:09