简体   繁体   中英

Hi I want to pass formdata with input type file but how can I do it?

I have this function when I change the input type file to insert into database, in Laravel.

$(document).on('change', '#galeria_imagen', function () {

    var elab = $('#elaboracion_ins').val();
    var formdata = new FormData();

    formdata.append("galeria_imagen", $('input[name=galeria_imagen]')[0].files[0]);

    console.log(prueba);
    $.ajax({
        type: 'POST',
        url: "/admin/elaboraciones/ajax/setGaleria",
        processData: false,
        data: formdata,
        success: function () {
            recargar_galeria(elab);
        }
    });
});

And always return me " Illegal invocation " and I put ProcessData:false and don't work for me because don't insert, in Laravel I need a base64 hash to insert a file.

Without seeing your HTML we can't really tell. But I think you're setting galeria_imagen as a name not an id , so that won't get you anywhere. Also, when you're inside a handler, the this context is actually the element itself, so you could simply do this.files[0] .

$(document).on('change', 'input[name="galeria_imagen"]', function() {
  var elab = $('#elaboracion_ins').val();
  var formdata = new FormData();

  formdata.append(this.name, this.files[0]);

  $.ajax({
    type: 'POST',
    url: "/admin/elaboraciones/ajax/setGaleria",
    processData: false,
    data: formdata,
    success: function() {
      recargar_galeria(elab);
    }
  });
});

add multipart/form-data as mime type

$(document).on('change', '#galeria_imagen', function () {

var elab = $('#elaboracion_ins').val();
var formdata = new FormData();

formdata.append("galeria_imagen", $('input[name=galeria_imagen]')[0].files[0]);

console.log(prueba);
$.ajax({
    type: 'POST',
    url: "/admin/elaboraciones/ajax/setGaleria",
    mimeType: "multipart/form-data",
    processData: false,
    contentType: false,
    data: formdata,

    success: function () {
        recargar_galeria(elab);
    }
});
});

Here is a boilerplate that works - see http://jsfiddle.net/09o71yjc/

$('form.uploader input:file').on('change', function() {

    var data = new FormData();
    data.append('file', this.files[0]);

    $.ajax({
        url: $('.uploader').attr('action'),
        type: 'POST',
        dataType: 'json',
        processData: false,
        data: data,
        success: function () {
            alert('Uploaded')
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM