Angular 11-Laravel 7 REST Api带图像的Put请求

Angular 11-Laravel 7 REST Api带图像的Put请求,angular,laravel,typescript,httpclient,put,Angular,Laravel,Typescript,Httpclient,Put,我想向Laravel API发送一个http put请求,该请求可能有一个图像文件,有时没有 这是我的密码: getEditCategory(): any { var category; var description = ''; if(this.description() != null) { description = this.description().value.trim(); } let imageAdded = false;

我想向Laravel API发送一个
http put请求
,该请求可能有一个图像文件,有时没有

这是我的密码:

getEditCategory(): any {
    var category;

    var description = '';
    if(this.description() != null) {
      description = this.description().value.trim();
    }
    let imageAdded = false;
    let image = null;
    let image_changed = false
    if(this.modal.button == 'Update Category') {
      if(this.imageChanged) {
        if(typeof this.selectedImage !== 'undefined') {
          image = this.selectedImage;
          imageAdded = true;
        }
       image_changed = true;
      }

      let category = {
        name: this.name().value.trim(),
        description: description,
        active: this.active().value,
        parent: this.parentCategory().value.data.id,
        imageAdded: imageAdded,
        image: image,
        image_changed: image_changed
      }
      return category;
    } else {
      let category = new FormData();
      category.append('name', this.name().value.trim());
      if(this.description() != null) {
        category.append('description', this.description().value.trim());
      }
      category.append('parent_id', this.parentCategory().value.data.id);
      category.append('active', this.active().value);
      if(typeof this.selectedImage !== 'undefined') {
        category.append('image', this.selectedImage, this.selectedImage.name);
        imageAdded = true;
      }
      return category;
    }
  }

 btnCategory(): void {
    let category = this.getEditCategory();

    let url = this.api + '/admin' + '/categories';
    if(this.modal.button == 'Update Category') {
      url += '/' + this.category.data.id;
      category.append('id', this.category.data.id);
      this.request.putRequestFormData(url, category).then(
        data => {
          console.log(data);
          // this.categories = data['categories'];
          this.modalService.close('modal-1');
          this.fillCategories();
        })
      .catch(
        error => {
          this.error = error.error;
          console.log(error);
          if (error.status === 404) {
            this.error.nativeElement.value = 'Invalid Request';
          }

          if (error.status == 401) {
            this.httpErrorsService.handle401();
            this.router.navigate(['login']);
          }

          this.error.nativeElement.style.display = 'block';
        }
      );
    }

    if(this.modal.button == 'Add Category') {
      this.request.postRequestFormData(url, category).then(
        data => {
          this.categories = data['categories'];
          this.modalService.close('modal-1');
          this.fillCategories();
        })
      .catch(
        error => {
          this.error = error.error;
          console.log(error);
          if (error.status === 404) {
            this.error.nativeElement.value = 'Invalid Request';
          }

          if (error.status == 401) {
            this.httpErrorsService.handle401();
            this.router.navigate(['login']);
          }

          this.error.nativeElement.style.display = 'block';
        }
      );
    }
  }
以下是请求服务中的put请求功能:

  putRequestFormData(url: string, data: FormData): Promise<HttpEvent<any>> {
    const options = {
      headers: new HttpHeaders({
        Accept:  'application/json',
        // I tried these lines but both didn't work
        // ContentType: 'multipart/form-data ',
        // ContentType: 'application/x-www-form-urlencoded',
        Authorization: 'Bearer ' + this.appStorage.getToken()
      })
    };

    return this.http.put<any>(url, data, options).toPromise();
  }

名称
名称是必需的
名称格式不正确
描述
描述格式不正确
活动/非活动
形象
取消
父母亲
{{category.data.name}

{{this.modal.button} 闭合模态
在服务器端,即Laravel REST Api,当我以
FormData
的形式发送PUT请求时,我接收到一个空的正文,但当我以
JSON
的形式发送时,它发送的正文没有图像!知道有时可能发送图像文件,有时可能不发送图像文件,如何解决此问题。

PS:post请求的代码工作正常


PS:现在我只使用POST请求发送图像,即使在更新时也是如此。如前所述,PUT请求仅在不涉及图像的情况下有效。如果您有修复程序,请编写。

您是否尝试将“多部分/表单数据”标题添加到您的请求中?没有,但我尝试了{Content Type':
application/x-www-form-urlencoded
}我把两者都绑定了,但它在postman中不起作用。它在
应用程序/x-www-form-urlencoded
上工作,但在Angular中不起作用。我认为只有
多部分/表单数据
接受laravel中的图像,但它不起作用
getNormalHeaders(): any {
    const options = {
      headers: new HttpHeaders({
        'Accept':  'application/json',
        Authorization: 'Bearer ' + this.appStorage.getToken()
      })
    };

    return options;
  }

postRequest(url: string, data: any): Promise<HttpEvent<any>> {
    const options = this.getNormalHeaders();
    url = this.api + url;
    return this.http.post<any>(url, data, options).toPromise();
  }
// This as a Component variable
selectedImage: File;
// This is the declaration of the form
 this.addCategoryForm = this.formBuilder.group({
        name: new FormControl('', [Validators.required]),
        description: new FormControl(''),
        parentCategory: new FormControl(this.parentCategories[0]),
        active: new FormControl(true),
        image: new FormControl()
      });
<!-- HTML form -->
<div class="form__group">
        <form [formGroup]="addCategoryForm" (ngSubmit)="btnCategory()">
            <div class="form__body">
                <div class="form-group">
                    <div class="row justify-content-center">
                        <div class="col-md-2">
                            <label class="form__label" for="name">Name</label>
                        </div>

                        <div class="col-md-5">
                            <input type="text" #name formControlName="name" class="col-md-8 form-control form__input"
                                placeholder="Name">
                            <div *ngIf="this.addCategoryForm.get('name').errors" class="error-form">
                                <div *ngIf="this.addCategoryForm.get('name').errors.required">Name is required</div>
                                <div *ngIf="this.addCategoryForm.get('name').errors.name">Incorrect Name Format
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="row justify-content-center">
                        <div class="col-md-2">
                            <label class="form__label" for="description">Description</label>
                        </div>

                        <div class="col-md-5">
                            <input type="text" #description formControlName="description"
                                class="col-md-8 form-control form__input" placeholder="Description">
                            <div *ngIf="this.addCategoryForm.get('description').errors" class="error-form">
                                <div *ngIf="this.addCategoryForm.get('description').errors.description">
                                    Incorrect description Format
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="row justify-content-center">
                        <div class="col-md-2">
                            <label class="form__label" for="active">Active/Inactive</label>
                        </div>

                        <div class="col-md-5">
                            <input type="checkbox" #active formControlName="active"
                                class="col-md-8 form-control form__checkbox" placeholder="Active">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="row justify-content-center">
                        <div class="col-md-2">
                            <label class="form__label" for="image">Image</label>
                        </div>

                        <div class="col-md-5" #file__div>
                            <input type="file" accept="image/png, image/gif, image/jpeg" #file formControlName="image"
                            (change)="showPreview($event)" class="col-md-9 form-control form__file">
                        </div>
                        <div class="col-md-8" *ngIf="imageURL && imageURL !== ''">
                            <div class="row justify-content-center">
                                <div style="direction:rtl; text-align:justify;" class="col-md-4 imagePreview">
                                    <img class="img-responsive" [src]="imageURL" [alt]="">
                                </div>
                                <div class="col-md-5">
                                    <button class="btn-danger-sm" (click)="clearImage()" type="button">Cancel</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="row justify-content-center">
                        <div class="col-md-2">
                            <label class="form__label" for="parent">Parent</label>
                        </div>
                        <div class="col-md-5">
                            <select #parent class="col-md-8 form-control select-modal" formControlName="parentCategory">
                                <option *ngFor="let category of parentCategories" [ngValue]="category">
                                    {{ category.data.name }}
                                </option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-group error-form">
                <label #error id="error"></label>
            </div>
            <hr />
            <div class="container">
                <div class="row justify-content-center">
                    <button class="btn-primary-sm" type="submit">{{ this.modal.button }}</button>
                    <button class="btn-danger-sm" type="button" (click)="modalService.close('modal-1')">Close Modal</button>
                </div>
            </div>
        </form>
    </div>