Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
ARTICLE

How to upload media through URL in Shopware 6

Overview

In this article we learn about how to upload media through URL in Shopware 6.

Media Upload Method

Collect the Media URL in an array and create a media repository. We need to add to services FileFetcher and FileSaver , if you are in custom service then also register   ContinerInterface.

We recommended the following  processor

<?php

namespace Webkul\BulkUpload\Services;

use Psr\Container\ContainerInterface;
use Shopware\Core\Content\Media\File\FileFetcher;
use Shopware\Core\Content\Media\File\FileSaver;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\HttpFoundation\Request;

class BulkUploadHelper 
{
    private $container;
    protected $fileFetcher;
    protected $fileSaver;

    public function __construct(
        ContainerInterface $container,
        FileFetcher $fileFetcher,
        FileSaver $fileSaver
    )
    {
        $this->container = $container;
        $this->fileFetcher = $fileFetcher;
        $this->fileSaver = $fileSaver;
    }

    public function uploadBulkImages($urlCollection, $salesChannelContext){
        $context = Context::createDefaultContext();
        $mediaRepository = $this->container->get('media.repository');
        $mediaIds = [];
        foreach($urlCollection as $url) {
            $ext = pathinfo($url, PATHINFO_EXTENSION);
            $fileName = basename($url, $ext);
            
            $request = new Request(['extension' => $ext], ['url' => $url]);
            $tempFile = tempnam(sys_get_temp_dir(), '');
            $file = $this->fileFetcher->fetchFileFromURL($request, $tempFile);
            $explodedFileName = explode('.', $fileName);
            unset($explodedFileName[count($explodedFileName) - 1]);
            $fileName = $salesChannelContext->getCustomer()->getId() . '_' . implode('.', $explodedFileName);
            $searchMedia = $mediaRepository->search((new Criteria())->addFilter(new EqualsFilter('fileName', $fileName)),$context)->first();
            if(!$searchMedia){
           
                $mediaId = Uuid::randomHex();
                $media = [
                    [
                        'id' => $mediaId,
                        'fileSize' => $file->getFileSize(),
                        'fileName' => $fileName,
                        'mimeType' => $file->getMimeType(),
                        'fileExtension' => $ext,
                    ]
                ];

                $mediaId = $mediaRepository->create($media, Context::createDefaultContext())
                    ->getEvents()
                    ->getElements()[1]
                    ->getIds()[0];
                if (is_array($mediaId)) {
                    $mediaId = $mediaId['mediaId'];
                }
            
                try {
                    $this->upload($file, $fileName, $mediaId);
                } catch (\Exception $exception) {
                    $fileName = $fileName . $mediaId;
                    $this->upload($file, $fileName, $mediaId);
                }
                array_push($mediaIds, [
                    'id' => $mediaId,
                    'title' => $fileName
                ]);
            }

        }
        return $mediaIds;
    }
    public function upload($file, $fileName, $mediaId)
    {   
        $this->fileSaver->persistFileToMedia(
            $file, 
            $fileName,
            $mediaId,
            Context::createDefaultContext()
        );
    }

}

In the above code we create a service for image upload, first of all we need to register our service into seervice.xml file for access globally. then pass argument into service, find below service.xml code..

<service id="bulkUpload.helper" class="Webkul\BulkUpload\Services\BulkUploadHelper" public="true">
   <argument type="service" id="service_container" />
   <argument type="service" id="Shopware\Core\Content\Media\File\FileFetcher"/>
    <argument type="service" id="Shopware\Core\Content\Media\File\FileSaver"/>
 </service>

passing service container, FileFetcher and FileSaver predefined services into our custom service. first of all define these service into class service constructor function for further use in our function.then create a function for upload media URL for Shopware6. Create default context object then create media repository from container. After this get extension of URL by this code pathinfo($url, PATHINFO_EXTENSION), then get filename from this method basename($url, $ext). Further create request object through URL and extension by this way new Request([‘extension’ => $ext], [‘url’ => $url]); and get tempFile of the image from this method tempnam(sys_get_temp_dir(), ”);

Through FileFetcher we can get the file object of URL passing request and tempFile.

I hope it will help you. Thanks for reading 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home