Passing an image file is unsuccessful using AJAX

This question already has an answer here:

  • Sending multipart/formdata with jQuery.ajax 11 answers

  • the problem should be on the parameter processData , please add the parameter processData: false, to your ajax request and try to get your image on the php.

                $.ajax({
                    url: formURL,
                    type: form.attr('method'),
                    dataType: 'json',
                    data: formData,//form.serialize(),
                    processData: false,  // tell jQuery not to process the data
                    contentType: false,   // tell jQuery not to set contentType
                    beforeSend: function(){},
                    success: function(data, textStatus, jqXHR) {},
                    error: function(jqXHR, textStatus, errorThrown) 
                   {
                      alert(jqXHR+ textStatus+ errorThrown);
                    },
                  complete: function(){}
                    });
    

    hope helps.good luck


    Place your inputs properly in one form and use FormData() to send the form as a whole. I would suggest something like this :

    <form method="post" enctype="multipart/formdata" id="myForm">
       <input type="text" name="title" />
       <input type="file" name="thumbnail" />
    </form>
    

    Build and send the data with js :

    var form = document.getElementById('myForm');
    var formData = new FormData(form);
    
    alert (formdata);
    
    $.ajax({
        url: "php/post-check.php",
        type: "POST",
        data: formData,
        success: function (data) {
            $("div#postresult").removeClass("alert alert-danger");
            $("div#postresult").html(data);
        }
    });
    

    Now you can get the data in php like this way :

    $title = $_POST['title'];
    $thumb = $_FILES['thumbnail'];
    $tmp_file_path = $thumb['tmp_name'];
    

    You could just post the entire form in async using ajaxForm() like this:

    $("#newpost").ajaxForm({
        success: function(data) {
            $("div#postresult").removeClass("alert alert-danger");
            $("div#postresult").html(data);
        },
        error: function(a, textStatus, exception) {
    
        }
    });
    

    AjaxForm is not part of core JQuery but you can find the source here and the documentation here

    链接地址: http://www.djcxy.com/p/48654.html

    上一篇: 通过一个平静的API上传图片的好习惯

    下一篇: 使用AJAX传递图片文件不成功