利用js/jq 利用FormData 对象和ajax上传文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiojing825/article/details/78795172

new FormData(); 可以获取某个表单,但是有时候感觉不太灵活。可以利用jq获取指定input type=file 中的文件,将其赋值给FormData 实例的某个属性,做上传。

HTML:

<div class="test" style="width: 200px;height: 200px; border: 1px solid">
    <input id="image" type="file">
</div>
<button id="upload">上传</button>

JS:

    $("#upload").click(function () {
        var file = $("#image")[0].files[0];
        //打印file 为对象
        console.log(file);

        var formObj = new FormData();
        formObj.set('image', file);
        $.ajax({
            url:'/test/upload',
            data:formObj,
            type: 'POST',
            dataType:'json',
            processData:false,
            contentType:false,
            success:function (res) {

            },
            fail : function (res) {

            }
        });
    });

对应的PHP方法中打印获取的文件信息。

function testFile() {

  print_r($_FILES);

}
/**
Array
(
    [image] => Array
        (
            [name] => red.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpXFXMw5
            [error] => 0
            [size] => 23989
        )
)
**/

猜你喜欢

转载自blog.csdn.net/xiojing825/article/details/78795172