I am making a form to create users, in this form I send a photo of the user. I have made the method in Laravel and to test the route for the creation of user and with image in postman does not generate any problem to me, the registry is created without problems. The detail I have is when I already use this method in AngularJS This is the function in angularjs:
$scope.btnCrearUsuario = function(item) {
$scope.item = item;
var fd = new FormData();
var file = item.avatar;
fd.append('avatar',file);
fd.append('nombre', item.nombre);
fd.append('apellido',item.apellido);
fd.append('usuario', item.usuario);
fd.append('password',item.password);
fd.append('idtipousuario', item.idtipousuario);
fd.append('correo', item.correo);
fd.append('telefono', item.telefono);
fd.append('estado', item.estado);
$http({
method: 'POST',
url: server+'ws/usuarios',
data: fd,
headers: {'Content-Type': undefined, 'Process-Data': false},
transformRequest: angular.identity
}).then( function() {
console.log('success');
}, function() {
console.log('failure');
});
}
I get the following error in console:
In this way I have made the method in laravel:
public function updateImage(Request $request, $id)
{
try
{
$nombre = "";
if ($request->hasFile("avatar")){
$temp = $request->file('avatar');
$destino = public_path()."\avatars";
$nombre = str_random(6).$temp->getClientOriginalName();
$subio = $temp->move($destino, $nombre);
if(!$subio)
throw new \Exception('No se pudo subir la foto');
}
$editarRegistro = \DB::transaction(function() use ($request, $id, $nombre)
{
$registro = Usuarios::find($id);
if (! $registro)
{
throw new \Exception("No existe el registro");
}
else
{
$registro->avatar = $nombre != "" ? $nombre : $registro->avatar;
$registro->nombre = $request->input('nombre', $registro->nombre);
$registro->apellido = $request->input('apellido', $registro->apellido);
$registro->usuario = $request->input('usuario', $registro->usuario);
if ($request->has('password') || $request->input('password') !="")
$registro->password = \Hash::make($request->input('password'));
$registro->idtipousuario = $request->input('idtipousuario', $registro->idtipousuario);
$registro->correo = $request->input('correo', $registro->correo);
$registro->telefono = $request->input('telefono', $registro->telefono);
$registro->estado = $request->input('estado', $registro->estado);
$registro->save();
return $registro;
}
});
$statusCode = 200;
$this->records = $editarRegistro;
$this->message = "Se edito correctamente el registro";
$this->result = true;
}
catch (\Exception $e)
{
$statusCode = 200;
$this->message = env('APP_DEBUG')?$e->getMessage():"El registro no se edito";
$this->result = false;
}
finally
{
$response =
[
'message' => $this->message,
'result' => $this->result,
'records' => $this->records
];
return response()->json($response, $statusCode);
}
}
Thank you in advance for the support.