Magento 2是目前最受欢迎的电子商务平台,通常会有很多从其他平台转移到M2的平台上来,这样在Magento 2中就需要从URL导入产品图像。默认情况下,Magento 2可以很好地处理图像导入,但是图片路径仅位于服务器中。然而,从外部URL导入产品图片时,可以使用以下解决方案。

以下内容可以包含在任何需要的地方,它的execute方法将使用以下参数调用::

  • $product  –加载的产品实例,图像将添加到其中
  • $imageUrl  –外部图片网址
  • $visible  –默认情况下将隐藏图像。您可以通过传递布尔值“true”使其可见。
  • $imageType  –数组,可选参数,您可以在其中指定将图像设置为主图像,小图像还是缩略图或它们的任意组合。

该帖子提供了从Magento 2商店中的外部URL轻松导入产品图像的解决方案。

在Magento 2中从URL导入产品图像的方法:

app/code/[Vendor]/[Module]/Service文件夹中创建ImportImageService.php类,并添加以下代码:

<?php
	namespace [Vendor]\[Module]\Service;
	
	use Magento\Catalog\Model\Product;
	use Magento\Framework\App\Filesystem\DirectoryList;
	use Magento\Framework\Filesystem\Io\File;
	
	class ImportImageService
	{
		protected $directoryList;
		protected $file;
		public function __construct(
			DirectoryList $directoryList,
			File $file
		) {
			$this->directoryList = $directoryList;
			$this->file = $file;
		}
		public function execute($product, $imageUrl, $visible = false, $imageType = [])
		{
			$tmpDir = $this->getMediaDirTmpDir();
			$this->file->checkAndCreateFolder($tmpDir);
			$newFileName = $tmpDir . baseName($imageUrl);
			$result = $this->file->read($imageUrl, $newFileName);
			if ($result) {
				$product->addImageToMediaGallery($newFileName, $imageType, true, $visible);
			}
			return $result;
		}
		protected function getMediaDirTmpDir()
		{
			return $this->directoryList->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp';
		}
	}

在将数据迁移到Magento 2时,上述解决方案证明是节省时间的。