I use js to assemble the data and then ajax to transmit it to the background. $request- > file () always cannot receive the file, and the file field passed by
is always converted into a string [object File] how to solve
foreground ajax code
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 PP )
{
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;
}
background code
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"));
}