我想将图像上传到现有产品。图像在中import_dir。并且需要将它们添加到目录中已经存在的产品中。
我只能找到两种方法。
1.“不良实践”方式-使用产品模型\Magento\Catalog\Model\Product::addImageToMediaGallery
1. Copy the images from `import_dir` to `pub/media/tmp`
2. Add the images to the product
3. Save product
码
    /* copy files from import_dir to pub/media/tmp */
    /** @var \Magento\Catalog\Api\Data\ProductInterface $product */
    /* Init media gallery */
    $mediaGalleryEntries = $product->getMediaGalleryEntries();
    if (empty($mediaGalleryEntries) === true){
        $product->setMediaGalleryEntries([]);
    }
    /* Add an image to the product's gallery */
    $product->addImageToMediaGallery(
        $filePathFromTmpDir,
        [
          "image",
          "small_image",
          "thumbnail",
          "swatch_image" 
        ],
        $moveImage,
        $disableImage
    );
    /* Save */
    $this->_productRepository->save($product);
2.“良好实践”方式- 使用API \Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface::create
1. Create image content object via **\Magento\Framework\Api\Data\ImageContentInterfaceFactory**
2. Create image object via **\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterfaceFactory**
3. Create an image via API
码
    $imageContent = $this->_imageContentInterfaceFactory->create()
        ->setBase64EncodedData(base64_encode(file_get_contents($filePathImportDir)))
        ->setType($this->_mime->getMimeType($filePathImportDir))
        ->setName($file_name);
    $newImage = $this->_productAttributeMediaGalleryEntryInterfaceFactory->create()
        ->setMediaType(\Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter::MEDIA_TYPE_CODE)
        ->setFile($filePathImportDir)
        ->setDisabled($disableImage)
        ->setContent($imageContent)
        ->setLabel('label');
    $this->_productAttributeMediaGalleryManagement->create($product->getSku(), $newImage);
顾虑:
- 在1我发现了一个错误,这是已知问题
未定义索引:media_type 
- 在2的方式太复杂,它应该是更简单的方法
问题:
- 是否有“最佳实践”方法来管理(添加,删除,替换)产品的图像?
- \ Magento \ CatalogImportExport \ Model \ Import \ Product也许有办法
$entry->setMediaType('image');行,我不太确定,因为我记得它引起了我一些错误,例如它需要类型“ png”或“ jpg”(所以最后应该是“ image / png”)。但是同样,我不确定