使用FormData上传AJAX图像;t在服务器端显示图像


AJAX image upload with FormData doesn't show image on server side

我正在制作一个图像上传系统,只要将图像附加到input[type='file']元素,就可以立即上传图像。然而,我在将图像发送到服务器端时遇到了困难。

测试用例

HTML:

<a class="button" data-action="upload-images">Upload Image</a>
<div style="display:none;">
    <form method="POST" enctype="multipart/form-data" class="image-upload-form">
        <input type="file" name="image" data-caller="upload-images" accept="image/*" />
        <input type="hidden" name="object_id" value="1"/>
    </form>
</div>

JavaScript:

// Let a custom button open the file selection frame
jQuery( document ).on( "click", "[data-action='upload-images']", function() {
    jQuery( this ).parent().find( "[data-caller='upload-images']" ).click();
});
// Catch a file upload
jQuery( document ).on( "change", "[data-caller='upload-images']", function() {
    jQuery.ajax({
        url: "ajax/image-upload",
        type: "POST",
        data:  new FormData( this.parentNode ),
        contentType: false,
        processData: false,
        success: function( data ) {
            console.log( data );
        }
    });
});

PHP:ajax/图像上传

var_dump($_POST);

测试

执行此代码会在控制台中给出以下输出:

array(1) {
    ["object_id"]=>
    string(1) "1"
} // No image?

请求有效载荷为:

------WebKitFormBoundaryi8mRsBbBQSmCgZ4f
Content-Disposition: form-data; name="image"; filename="TrueTone.png"
Content-Type: image/png

------WebKitFormBoundaryi8mRsBbBQSmCgZ4f
Content-Disposition: form-data; name="object_id"
1
------WebKitFormBoundaryi8mRsBbBQSmCgZ4f--

我尝试过的

我真的找不到将上传的图像上传到服务器端的方法。到目前为止,我已经看到了一些教程,它们使用相同的方法,但捕获文件上传onSubmit并使用e.preventDefault来取消实际提交。我用提交按钮完全重写了我的代码,以复制这种捕捉图像的方式,但没有成功。

请求负载指示文件正在上传,但在服务器端看不到。我希望你能帮助我。

使用print_r($_FILES)检查是否发送了任何文件而不是$_POST