鍍金池/ 問(wèn)答/PHP  HTML/ 關(guān)于laravel ajax上傳圖片的問(wèn)題

關(guān)于laravel ajax上傳圖片的問(wèn)題

我用js拼裝數(shù)據(jù) 然后ajax傳到后臺(tái),$request->file()總是接收不到文件,
傳過(guò)去的file字段總是會(huì)被轉(zhuǎn)換成字符串 [object File] 請(qǐng)問(wèn)如何解決

前臺(tái)ajax代碼

onAjax(formObj,dataType)
    {
        var that = this;
        var form = $(formObj)[0];
        var data = this._formToData(form);
        var url = form.action;
        var type = form.method;
        $.ajax({
            sync : false,
            url : url ,
            data : data ,
            type : type ,
            dataType : dataType ? dataType : 'json',
            success(r)
            {
                console.log(r);
            },
            complete(r)
            {
                console.log(r);
                var response = r.responseJSON;
                var status = r.status;
                if(status === 200)
                {
                    return that.showNotifies(response.msg,'success');
                }
                that._getResponseError(response.errors);
                return that.showNotifies(response.message,'danger');
            }
        });
        return false;
    },
    _formToData(form)
    {
        var i = 0;
        var data = [];
        for (i ; i < form.length ; i ++ )
        {
            if(form[i].name)
            {
                if(form[i].type == 'file')
                {
                    data.push({
                        name : form[i].name,
                        value : $(form[i])[0].files[0]
                    });
                }else{
                    data.push({
                        name : form[i].name,
                        value : form[i].value
                    });
                }
            }
        }
        return data;
    }

后臺(tái)代碼

public function edit($id,Request $request)
    {
        $this->_checkIsLoginUser($id);
        $user = User::find($id);


        $this->validate($request, [
            'firstName' => 'nullable|max:10',
            'lastName' => 'nullable|max:10',
            'contact' => 'nullable|integer',
            'birthday' => 'nullable|date|max:10',
            'address' => 'nullable|string|max:200',
            'city' => 'nullable|string|max:50',
            'country' => 'nullable|string|max:50',
            'postal' => 'nullable|integer',
            'aboutMe' => 'nullable|string|max:255'
        ]);

        $path = $request -> file('avatar');
        $data = $request -> input();
        $data['avatar'] = $path;
        unset($data['_token']);

        $user -> info = json_encode($data);
        $res = $user -> save();
        if($res)
        {
            return $this->_toAjax(__('notices.update.success'));
        }
        return $this->_toAjax(__('notices.update.danger'));
    }
回答
編輯回答
命于你

使用 FormData。

你的問(wèn)題應(yīng)該是使用了錯(cuò)誤的 mimetype

2018年5月1日 05:22