PHP简单实现异步多文件上传并使用Postman测试提交图片

2023/5/12 23:22:16

本文主要是介绍PHP简单实现异步多文件上传并使用Postman测试提交图片,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

虽然现在很多都是使用大平台的对象存储存放应用中的文件,但有时小项目还是可以使用以前的方式上传到和程序一起的服务器上,强调一下这里是小众需求,大众可以使用阿里云的OSS,腾讯的COS,七牛的巴拉巴拉xxxxxx……

Postman使用

1. 打开后,选择"body"->"form-data",key悬浮的时候选择“File”, 然后value会出现一个文件按钮。

https://img4.sycdn.imooc.com/645cac2a0001c23b09990346.jpg

2. 本地的上传方法测试一下打印一下。

https://img4.sycdn.imooc.com/645cac2a00010dc803400148.jpg

https://img3.sycdn.imooc.com/645cac2b00019bef07430300.jpg

3. 以上使用Postman测试文件上传接口就通了,下面就写一个异步上传的效果。

 

多文件异步上传

1. 前端

<!--图片上传-->            <div class="row cl">
                <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span> 图片:</label>
                <div class="formControls col-xs-8 col-sm-3">
                    <input id="img" type="file" multiple="true" onchange="uploadImgs(this,event)"/>
                    <div id="img_box">
                        <foreach name="img_upload.img_arr" item="data">
                        <div class="img_item">
                            <img id="ImgPr" class="hid" class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{$data.url}"/>
                            <span class="del hid" onclick="closeImg(this)">X</span>
                        </div>
                        </foreach>
                    </div>

                    <input id="hid_img" type="hidden" name="img" value="{$img_upload['img_str']}"/>
                </div>
            </div>
            <!--图片上传-->// 多图片上传触发事件
        function uploadImgs(_this,event) {            // 实例FormData
            var data = new FormData();            for (var i = 0; i < event.target.files.length; i++) {                var files = event.target.files[i];                // 批量添加文件
                data.append('file[]', files);
            }            // 异步提交
            ajaxUpload(data);
        }        function ajaxUpload(data) {

            $.ajax({                url: '{$ajax_upload_url}',                type: "POST",                data: data,                dataType: 'json',                processData: false,// *重要,确认为false
                contentType: false,                // beforeSend: function () {
                //     console.log(11111);
                // },
                success: function (res) {                    if(res.error == 1) {                        alert(res.msg);                        return;
                    }else {                        console.log(res);                        var imgArr = $("#hid_img").val();
                        $.each(res.data,function(index,data) {                            // 追加显示
                            $("#img_box").append(                                '<div class="img_item">'+                                    '<img id="ImgPr" class="hid" class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="'+data.path+'"/>'+                                    '<span class="del hid" onclick="closeImg(this)">X</span>'+                                '</div>'
                            );                            if(!imgArr) {
                                imgArr = data.path;
                            }else {
                                imgArr += ","+data.path;
                            }                            // 追加提交数据
                            //$(".formControls").append('<input id="hid_img" type="hidden" name="img[]" value="'+data.path+'"/>');
                        })
                        $("#hid_img").val(imgArr);
                    }
                },                error: function (res) {                    alert('异步上传图片接口出错');                    return;
                }
            });
        }

 https://img4.sycdn.imooc.com/645cac2b0001a7e507380358.jpg

https://img3.sycdn.imooc.com/645cac2c00019c5506190655.jpg

2. PHP部分就是和同步方式一样。

 /*
     * 图片上传
     * */
    public function ajaxUpload() {        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小 3145728
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
        $upload->savePath  =     'repair/'; // 设置附件上传(子)目录
        // 上传文件
        $info   =   $upload->upload();        if(!$info) {// 上传错误提示错误信息
            $this->ajaxReturn(array("error"=>1,"msg"=>$upload->getError(),"data"=>array()));
        }else{// 上传成功
            $uploadFile = array();            foreach($info as $key=>$value) {                $uploadFile[] = array(                    "path" => ltrim($upload->rootPath,'.').$value['savepath'].$value['savename'],                    "ext" => $value['ext'],
                );
            }            $this->ajaxReturn(array("error"=>0,"msg"=>"上传成功","data"=>$uploadFile));
        }
    }

 





这篇关于PHP简单实现异步多文件上传并使用Postman测试提交图片的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程