简体   繁体   中英

Problems to upload a file from Angular 7 to Laravel

I'm searching a lot but no question resolves my problem, I'm trying to send a simple image to a server in my Laravel 6.6 version.

This is my Angular 7 side

    const formData = new FormData();
    formData.append('file', this.files[0]);

    this.categoryService.store(category, formData).subscribe(
      response => { console.log(response); },
      error => {
        console.log(error);
      }
    );

  public store(categoryData: CategoryModel, filesData: FormData): Observable<any> {
    return this.http.post(this.mainConfig.config.default.mainUrl + this.STORE_CATEGORY_URL, filesData)
   .pipe(timeout(this.timeOut));
  }

And in my Laravel side, I just want to check if the file is arrive

    if($request->hasFile('file')) {
        $response["success"] = 1;
        $response["message"] = "Tem um arquivo";
        return $response;
    } else {
        $response["success"] = 0;
        $response["message"] = "Não tem um arquivo";
        return $response;
    }

I found my problem I have a token-interceptor for every request for my API, that is like this:

  const newRequest = request.clone({
        setHeaders: {
          Authorization: `Bearer ${this.token}`
        },
        body: {
          ...request.body,
          companyCode: this.userData.companyCode,
        },
      });

When I remove this line

   body: {
              ...request.body,
              companyCode: this.userData.companyCode,
            },

It works fine, I use this to send the company code for my tenant database connection on the backend and in every request, I send the companyCode, but when i use this with formData is not working why?

The upload should be always done using the put request on httpClient because file upload will be done in the smaller chunks(4kb). post can't transmit continuously and will only cut once the first chunk is transferred. You can directly use the file as the body. You should not use FormData for images because it appends the FormData headers and corrupts the image.

this.categoryService.store(category,this.selectedFile).subscribe(
      response => { console.log(response); },
      error => {
        console.log(error);
      }
    )

Modify the service as follows

 public store(categoryData: CategoryModel,selectedFile:any): Observable<any> {
    return this.http.put(this.mainConfig.config.default.mainUrl + this.STORE_CATEGORY_URL, selectedFile)
   .pipe(timeout(this.timeOut));
  }

I resolve my problem checking the instance of the FormData and now it is working

if (!!this.token) {
          let newRequest;
          if (request.body instanceof FormData) {
            const formData = request.body;
            formData.append('companyCode', this.userData.companyCode);
            newRequest = request.clone({
              setHeaders: {
                Authorization: `Bearer ${this.token}`
              },
            });
            return next.handle(newRequest);
          } else {
            newRequest = request.clone({
              setHeaders: {
                Authorization: `Bearer ${this.token}`
              },
              body: {
                ...request.body,
                companyCode: this.userData.companyCode,
              },
            });
            return next.handle(newRequest);
          }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM