file_put_contents()上传图片的问题

问题描述

前端用ajax把base64格式的图片传过来,能成功保存,但是不知为何会多生成一个图片。

相关代码

uploadImg () {
                this.$http.post(this.$store.state.apiUrl + 'uploadImg', [
                    this.image
                ]).then(function (response) {
                    console.log(JSON.stringify(response.body));
                }, function (response) {
                    console.log(JSON.stringify(response.body));
                });
            }
// php部分
        define('UPLOAD_DIR', './uploads/');
        $img = $this->request->post(0);
        $start=strpos($img,',');
        $img= substr($img,$start+1);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);

        $fileName = UPLOAD_DIR . uniqid() . '.jpg';
        $success = file_put_contents($fileName, $data);
        $data=array();
        if($success){
            $data['status']=1;
            $data['msg']= $img;
            echo json_encode($data);
        }else{
            $data['status']=0;
            $data['msg']='系统繁忙,请售后再试';
            echo json_encode($data);
        }

你期待的结果是什么?实际看到的错误信息又是什么?

多生成了右边这个空白的图片

clipboard.png

阅读 4.1k
3 个回答

从图片名字看,应该是前端发起了多次请求造成

可以检查浏览器调试器里的network是否发起多次请求

同意楼上说法, 你生成的两个文件名已经是不一样的了,肯定是多次请求造成的了

同意楼上的,限制前端一次刷新提交即可,或者你在后台进行限制

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题