鍍金池/ 問答/PHP/ file_put_contents()上傳圖片的問題

file_put_contents()上傳圖片的問題

問題描述

前端用ajax把base64格式的圖片傳過來,能成功保存,但是不知為何會多生成一個(gè)圖片。

相關(guān)代碼

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']='系統(tǒng)繁忙,請售后再試';
            echo json_encode($data);
        }

你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?

多生成了右邊這個(gè)空白的圖片

clipboard.png

回答
編輯回答
無標(biāo)題

從圖片名字看,應(yīng)該是前端發(fā)起了多次請求造成

可以檢查瀏覽器調(diào)試器里的network是否發(fā)起多次請求

2017年3月18日 03:41
編輯回答
失心人

同意樓上的,限制前端一次刷新提交即可,或者你在后臺進(jìn)行限制

2017年4月5日 05:26
編輯回答
不舍棄

同意樓上說法, 你生成的兩個(gè)文件名已經(jīng)是不一樣的了,肯定是多次請求造成的了

2017年9月28日 05:09