Передача массива объектов в конечную точку с использованием Angular - PullRequest
0 голосов
/ 26 сентября 2019

У меня есть запрос на публикацию, в котором формат публикуемых данных выглядит следующим образом:

{
    "gallery": [{
        "id": 606,
        "status": 1,
        "name": "00000000606.png",
        "title": "splash.png",
        "location": "",
        "caption": "",
        "type": "image/png",
        "charset": "binary",
        "tags": "",
        "width": 2732,
        "height": 2732,
        "size": 476358,
        "embed_id": null,
        "user": 1,
        "date_uploaded": "2019-09-26T05:22:31-04:00",
        "storage_adapter": "local",
        "url": "/storage/uploads/00000000606.png",
        "thumbnail_url": "/storage/uploads/thumbs/606.png",
        "old_thumbnail_url": "/storage/uploads/thumbs/00000000606-png-160-160-true.jpg",
        "html": null
    }, {
        "id": 610,
        "status": 1,
        "name": "00000000610.png",
        "title": "icon.png",
        "location": "",
        "caption": "",
        "type": "image/png",
        "charset": "binary",
        "tags": "",
        "width": 1024,
        "height": 1024,
        "size": 274477,
        "embed_id": null,
        "user": 1,
        "date_uploaded": "2019-09-26T06:43:44-04:00",
        "storage_adapter": "local",
        "url": "/storage/uploads/00000000610.png",
        "thumbnail_url": "/storage/uploads/thumbs/610.png",
        "old_thumbnail_url": "/storage/uploads/thumbs/00000000610-png-160-160-true.jpg",
        "html": null
    }]
}

Затем создается слайд-шоу галереи после отправки данных.

Чтобы скомпилировать этот массив, я сначала загрузил изображения, используя функцию перетаскивания.Это загружает в конечную точку каталога файлов и при успешном возвращении в ответ помещается в массив в локальном хранилище.Приведенные выше данные являются массивом локальных объектов хранения.Так что выглядит хорошо, пока я не попытаюсь отправить его обратно.

После заполнения оставшейся части формы я отправляю значения формы, используя метод post.Все данные, кажется, сформированы правильно, но сервер отвечает с ошибкой 500.

ошибка (которая не будет знакома некоторым), поскольку я использую Directus Headless CMS

эта ошибка возникает при отправке сообщений от Почтальона, так как я не получаю много ответов в отношении сообщения об ошибке.

{
    "success": false,
    "error": {
        "message": "File not found at path: "
    },
    "code": 0,
    "class": "League\\Flysystem\\FileNotFoundException",
    "file": "/homepages/5/d755856449/htdocs/demo/vendor/league/flysystem/src/Filesystem.php",
    "line": 386
}

.html

это виновник в представлении:

<label tooltip="Add images of the product here" placement="right" show-delay="500">Product Gallery<span
            class="question">?</span></label>
  <ngx-file-drop dropZoneLabel="Drop files here" (onFileDrop)="galleryFilesDropped($event)"
        (onFileOver)="fileOver($event)" (onFileLeave)="fileLeave($event)">
        <ng-template ngx-file-drop-content-tmp let-openFileSelector="openFileSelector">
            Drag &amp; Drop your Gallery Images onto Here.
            <button class="update" type="button" (click)="openFileSelector()">Browse Files</button>
        </ng-template>
  </ngx-file-drop>
  <label>Gallery Images</label>
  <div class="gallery">
     <ng-container *ngIf="!selectedGallery.length">
         <div class="no_articles">
             <img src="../../../assets/img/no_content-01.svg" alt="no-content icon">
             <p>Currently, no gallery images exist, upload them above</p>
         </div>
     </ng-container>
     <ng-container *ngFor="let image of selectedGallery">
         <span>
             <img class="placeholder" [src]="imageUrl + image.url" alt="selected image thumbnail">
             <button class="delete" (click)="deleteImage()">Remove</button>
         </span>
     </ng-container>
 </div>

и в component.ts, это методы drop и post

image-dropметод

public galleryFilesDropped(galleryImages: NgxFileDropEntry[], imageFile) {
    this.galleryImages = galleryImages;
    for (const droppedImage of galleryImages) {
      if (droppedImage.fileEntry.isFile) {
        const imageEntry = droppedImage.fileEntry as FileSystemFileEntry;
        imageEntry.file((image: File) => {
          let reader = new FileReader();
          reader.readAsDataURL(image);
          reader.onload = () => {
            let data = reader.result;
            let imageUpload = {
              title: image.name,
              name: image.name,
              type: image.type,
              size: image.size, data
            }
            this.configService.uploadImage(imageUpload)
            .subscribe(
              response => {
                  if (response) {
                  imageFile = response.data;
                  if (localStorage) {
                  var selectedImages;
                  if (!localStorage['selectedImages']) selectedImages = [];
                    else selectedImages = JSON.parse(localStorage['selectedImages']);
                    if (!(selectedImages instanceof Array)) selectedImages = [];
                    selectedImages.push(imageFile);
                    localStorage.setItem('selectedImages', JSON.stringify(selectedImages));
                    this.storageSubject.next(selectedImages);
                  }
                }
              }
            )
        }
      });
    } else {
      const imageEntry = droppedImage.fileEntry as FileSystemDirectoryEntry;
      console.log(droppedImage.relativePath, imageEntry)
    }
  }
}

метод postProduct

postProduct() {
    let productCreate = {
      product_category: this.selectedCategory, //posts fine
      product_thumbnail: this.selectedImage,//posts fine
      gallery: this.selectedGallery, <-- this doesn't send and breaks it
      product_name: this.product_name,//posts fine
      price: this.price,//posts fine
      product_description: this.product_description,//posts fine
      available_in_small: this.available_in_small,//posts fine
      available_in_medium: this.available_in_medium,//posts fine
      available_in_large: this.available_in_large,//posts fine
      available_in_extra_large: this.available_in_extra_large,//posts fine
      product_web_link: this.product_web_link,//posts fine
      ad_click: this.ad_click//posts fine
    }
    this.storeService.createProduct(productCreate)
      .subscribe(
        response => {
          if (response) {
            this.product = response.data;
          }
        }
      )
}

Я попытался установить значение ключа галереи на:

gallery: {
  data: JSON.parse(localStorage.getItem('selectedImages'))
},

и та же проблема возникает.Ошибка 500 возвращается неизвестно, но из того, что я узнал, работая с этой безголовой CMS, это будет связано с форматом данных, которые вызывают это.

У меня нет идей, попробовав диапазонразличных способов заставить это работать, и теперь я исчерпал свои предметные знания и силу поиска, чтобы найти решение.Может ли какой-нибудь умный человек подсказать, что я здесь делаю не так?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...