Ajax upload Image

2019-08-19 06:38发布

问题:

i'm trying to upload image using ajax on file image name changing but i can't get the $_FILES["InputUploadFileImage"]["tmp_name"]; on the server side my code.

JQuery Code

  $('#InputUploadFileImage').change(function() {
        var FilePath = $('#InputUploadFileImage').val();
        var FileSize = this.files[0].size;

        $.ajax({
            type: "POST",
            async: true,
            dataType: "json",
            url: ajaxurl,

            data: ({
                type: "POST",
                action: 'Ajax_ChangingProfileImage',
                FilePath: FilePath,
                FileSize: FileSize
            }),
            success: function (response) {
                if (response.Message === 'ImageSuccessfullyUploaded') {
                    alert('Image Successfully Uploaded.');
                    $('#imgUserImage').image_src = FilePath;
                    console.log(response.FilePath);
                } else {
                    alert('Image was not uploaded successfully.');
                    $('#imgUserImage').image_src = FilePath;
                    console.log(response.FilePath);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
    });

PHP Code

function Ajax_ChangingProfileImage() {

    $FileTmpPath = $_FILES["InputUploadFileImage"]["tmp_name"];
    $FileSize = $_POST['FileSize'];
    $FilePath = $_SERVER['DOCUMENT_ROOT'] . "restronaut/wp-content/uploads/UsersImages/1.jpg";
    $IsUploaded = move_uploaded_file($FileTmpPath ,$FilePath);

    if ($IsUploaded) {
        $response['Message'] = 'ImageSuccessfullyUploaded';
        $response['FilePath'] = $FilePath;

    } else {
        $response['Message'] = 'ImageNotSuccessfullyUploaded';
        $response['FilePath'] = $FilePath;
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    die();
}

please any help and many thanks in advance..

回答1:

You need to use new formData() to send image using ajax call. This is equal to setting an enctype in a regular form (without ajax)

for more info on the formData object here's a MDN link for you.

JQuery Code

$('#InputUploadFileImage').change(function() {
    /*var FilePath = this.files[0];
    var FileSize = this.files[0].size;
     var file = this.files[0];
    var name = FilePath.name;
    var type = FilePath.type;*/
    var formData = new FormData($('*formId*')[0]);
    $.ajax({
        type: "POST",
        async: true,
        dataType: "json",
        url: ajaxurl,

        data: ({
            type: "POST",
            action: 'Ajax_ChangingProfileImage',
            formData : formData 
        }),
        success: function (response) {
            if (response.Message === 'ImageSuccessfullyUploaded') {
                alert('Image Successfully Uploaded.');
                $('#imgUserImage').image_src = FilePath;
                console.log(response.FilePath);
            } else {
                alert('Image was not uploaded successfully.');
                $('#imgUserImage').image_src = FilePath;
                console.log(response.FilePath);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });
});

PHP Code

print_r($_FILES);


回答2:

I'm afraid you can't fetch the value of a file upload box via JavaScript. Therefore you cannot submit a file upload via Ajax in the same way you would standard text data.

Instead you must use JavaScript's FormData object to wrap the file into a multipart/form-data post data object. Please refer to the accepted answer in this StackOverflow question:

Upload File With Ajax XmlHttpRequest

Be aware that the FormData API is not supported by Internet Explorer 9-.