繁体   English   中英

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

[英]Problems to upload a file from Angular 7 to Laravel

我搜索了很多,但没有问题可以解决我的问题,我正在尝试将一个简单的图像发送到我的 Laravel 6.6 版本中的服务器。

这是我的 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));
  }

在我的 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;
    }

我发现我的问题我的 API 的每个请求都有一个令牌拦截器,就像这样:

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

当我删除这一行

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

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

上传应始终使用httpClient上的put请求完成,因为文件上传将在较小的块 (4kb) 中完成。 post不能连续传输,只有在传输第一个块后才会剪切。 您可以直接使用该file作为正文。 您不应将FormData用于图像,因为它会附加FormData标头并损坏图像。

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

修改服务如下

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

我解决了检查 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