沙滩星空的博客沙滩星空的博客

纯JS实现文件上传

HTML表单

<form id="my-form" class="am-form tpl-form-line-form" enctype="multipart/form-data" method="post">
......
<input id="wx-img-file" name="wxfile" type="file" multiple="multiple" required>
<input id="ali-img-file" name="alifile" type="file" multiple="multiple" required>
......
</form>

JS上传,包含表单信息。

<script>
    function uploadPic(type) {
        var form = document.getElementById('my-form'),
            formData = new FormData(form);
        console.log(formData)
        $.ajax({
            url:"upload?type="+type,
            type:"post",
            data:formData,
            processData:false,
            contentType:false,
            success:function(res){
                if(res){
                    alert("上传成功!");
                }
            resData = JSON.parse(res);
            $("#"+type+"-img-input").val(resData.url);
            $("#" + type +"-img").attr("src","/"+resData.url);
            },
            error:function(err){
                alert("网络连接失败,稍后重试",err);
            }

        })

    }
    $('#ali-img-file').on('change', function () {
        uploadPic('ali');
        var fileNames = '';
        $.each(this.files, function () {
            fileNames += '<span class="am-badge am-badge-success">' + this.name + '</span> ';
        });
        $('.file-list').html(fileNames);
    });
</script>

服务端处理逻辑

PHP CODE
    public function upload($type){
        $fileKeyMap = [
          'ali' => 'alifile',
          'wx' => 'wxfile',
        ];
        $fileKey = $fileKeyMap[$type];
        $imgname = $type . date('YmdHis',time()) . rand(1000,9999);// $_FILES['myfile']['name'];
        $tmp = $_FILES[$fileKey]['tmp_name'];
        $filepath = 'uploads/';
        if(move_uploaded_file($tmp,$filepath.$imgname.".png")){
            echo "上传成功";
        }else{
            echo "上传失败";
        }
    }

服务端接收的文件信息如下

print_r($_FILES)
Array
(
    [wxfile] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [alifile] => Array
        (
            [name] => bike.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpZYgqA5
            [error] => 0
            [size] => 2936
        )

)

简单实现js上传文件功能 https://www.jb51.net/article/121757.htm
未经允许不得转载:沙滩星空的博客 » 纯JS实现文件上传

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址