关于laravel ajax上传图片的问题

我用js拼装数据 然后ajax传到后台,$request->file()总是接收不到文件,
传过去的file字段总是会被转换成字符串 [object File] 请问如何解决

前台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;
    }

后台代码

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'));
    }
阅读 1.8k
1 个回答

使用 FormData

你的问题应该是使用了错误的 mimetype

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