简体   繁体   English

将文件从 Angular 7 上传到 Laravel 的问题

[英]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.我搜索了很多,但没有问题可以解决我的问题,我正在尝试将一个简单的图像发送到我的 Laravel 6.6 版本中的服务器。

This is my Angular 7 side这是我的 Angular 7 一面

    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在我的 Laravel 方面,我只想检查文件是否到达

    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:我发现我的问题我的 API 的每个请求都有一个令牌拦截器,就像这样:

  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?它工作正常,我使用它在后端发送我的租户数据库连接的公司代码,在每个请求中,我发送 companyCode,但是当我将它与 formData 一起使用时,为什么不起作用?

The upload should be always done using the put request on httpClient because file upload will be done in the smaller chunks(4kb).上传应始终使用httpClient上的put请求完成,因为文件上传将在较小的块 (4kb) 中完成。 post can't transmit continuously and will only cut once the first chunk is transferred. post不能连续传输,只有在传输第一个块后才会剪切。 You can directly use the file as the body.您可以直接使用该file作为正文。 You should not use FormData for images because it appends the FormData headers and corrupts the image.您不应将FormData用于图像,因为它会附加FormData标头并损坏图像。

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我解决了检查 FormData 实例的问题,现在它正在工作

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);
          }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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