1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Upload file from Angular to Laravel not working

Discussão em 'Angular' iniciado por Adrian2895, Agosto 10, 2025.

  1. Adrian2895

    Adrian2895 Guest

    I need to upload files from Angular to my Laravel API, but my code does not work and I cannot find where is the problem.

    user-edit.html (Angular):

    <div class="form-group">
    <label for="image">Avatar</label>
    <input type="file" (change)="avatarUpload($event)" name="image" class="form-control"/>
    </div>


    user-edit.ts (Angular):

    import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { UserService } from '../../services/user'

    @Component({
    selector: 'app-user-edit',
    imports: [FormsModule],
    templateUrl: './user-edit.html',
    styleUrl: './user-edit.css',
    providers: [UserService]
    })

    export class UserEdit {
    public token:string;

    constructor(
    private _userService: UserService
    ) {
    this.token = this._userService.getToken();
    }

    // Method for file uploading
    avatarUpload(data: any) {
    let file: File = data.target.files[0];
    if (file) {
    this._userService.avatarUpload(this.token, file).subscribe({
    next: (response) => {
    console.log(response)
    },
    error: (error) => {
    console.log(error);
    }
    })
    }
    }
    }


    user.ts (Angular):

    avatarUpload(token:string, file: File): Observable<any> {
    let formData = new FormData();
    formData.append('file0', file);

    // My API uses authorization, so I set it in the headers
    let headers = new HttpHeaders().set('Content-Type', 'application/form-data').set('Authorization', token);

    return this._http.post(this.url + 'user/upload', formData, {headers: headers});
    }


    UserController.php (Laravel):

    public function upload(Request $request) {

    $image = $request->file('file0');

    $validate = \Validator::make($request->all(), [
    'file0' => 'required|image|mimes:jpg,jpeg,png,gif'
    ]);


    if(!$image || $validate->fails()) {
    $data = array (
    'code' => 400,
    'status' => 'error',
    'message' => 'Error al subir imagen.'
    );

    } else {
    $image_name = time().$image->getClientOriginalName();
    \Storage::disk('users')->put($image_name, \File::get($image));

    $data = array(
    'code' => 200,
    'status' => 'success',
    'image' => $image_name
    );
    }


    If I try to upload a .png file from Angular, I keep getting error:

    [​IMG]

    On the other hand, if I try my backend code using Postman, it works perfectly:

    [​IMG]

    What is wrong in my code?

    Continue reading...

Compartilhe esta Página