1

This is My File Uploader in .phtml file :

<input type="file" id="imageUploader"  name="imageUploader">

This my PHP file code where form post.

<?php
namespace VendorName\ExtensionName\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()
    {
    $tmpDir = $this->getMediaDirTmpDir();
        /** create folder if it is not exists */
    $this->file->checkAndCreateFolder($tmpDir);
        /** @var string $newFileName */
    //$imageUrl='file:///home/chakko/Downloads/mywatch.jpg';
    $imageUrl=$_FILES['imageUploader']['name'];

    $newFileName = $tmpDir . baseName($imageUrl);
        /** read file from URL and copy it to the new destination */
    $result = $this->file->read($imageUrl, $newFileName);
    if ($result) {
            /** add saved file to the $product gallery */
            $product->addImageToMediaGallery($newFileName, $imageType, true, $visible);
     }
       return $result;
    }
    /**
     * Media directory name for the temporary file storage
     * pub/media/tmp
     *
     * @return string
     */
    protected function getMediaDirTmpDir()
    {
        return $this->directoryList->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp';
    }
}

The Problem is when I give manually path of the image like $imageUrl='file:///home/chakko/Downloads/mywatch.jpg'; is work good.

But when use fileuploader like this $imageUrl=$_FILES['imageUploader']['name']; it will not read the file .

Can any will help me i will be appriciate him

Ref: https://www.atwix.com/magento-2/import-product-image-from-url/

0

I've had mixed results with the method you have used

Instead I do this

public function __construct(
    \Magento\Catalog\Model\Product\Gallery\Processor $galleryProcessor,
} {
    $this->galleryProcessor = $galleryProcessor;
}

https://github.com/DominicWatts/Faker/blob/master/Helper/Product.php#L351

$this->galleryProcessor->addImage($product, $newFileName.'.jpg', $imageType, false, $visible);

Which is below in core

https://github.com/magento/magento2/blob/2.3/app/code/Magento/Catalog/Model/Product/Gallery/Processor.php#L133-L154

    /**
     * Add image to media gallery and return new filename
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param string $file file path of image in file system
     * @param string|string[] $mediaAttribute code of attribute with type 'media_image',
     *                                                      leave blank if image should be only in gallery
     * @param boolean $move if true, it will move source file
     * @param boolean $exclude mark image as disabled in product page view
     * @return string
     * @throws \Magento\Framework\Exception\LocalizedException
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @since 101.0.0
     */
    public function addImage(
        \Magento\Catalog\Model\Product $product,
        $file,
        $mediaAttribute = null,
        $move = false,
        $exclude = true
    ) {

Anyway I use it as part of

    public function addImageFromUrl($product, $imageUrl, $visible = false, $imageType = [])
    {
        $tmpDir = $this->getMediaDirTmpDir();
        $this->file->checkAndCreateFolder($tmpDir);
        $newFileName = $tmpDir.basename($imageUrl);
        /** read file from URL and copy it to the new destination */
        $result = $this->file->read($imageUrl, $newFileName);
        $this->file->cp($newFileName, $newFileName.'.jpg');
        if ($result) {
            try {
                // $product->addImageToMediaGallery($newFileName . '.jpg', $imageType, true, $visible);
                $this->galleryProcessor->addImage($product, $newFileName.'.jpg', $imageType, false, $visible);
            } catch (\Exception $e) {
                $this->logger->critical($e);
            }
        }
        return $result;
    }

Maybe that's a bit difficult to follow but I fetch images from an external source.

    const PLACEHOLDER_SOURCE = 'http://lorempixel.com/1000/1000';

    public function addImages(\Magento\Catalog\Model\Product\Interceptor $product, $limit = 1)
    {
        for ($generate = 1; $generate <= $limit; $generate++) {
            $this->addImageFromUrl($product, self::PLACEHOLDER_SOURCE, true, $generate == 1
                ? ['image', 'small_image', 'thumbnail'] : []);
        }
    }

And set first image as default for 'image', 'small_image', 'thumbnail'

Works for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.