I want to upload images using graphql, can anyone tell me how can I implement this?
Let me know if anyone has any idea.
First convert your image into base64 then use that base64 string in to graphql input.
<?php
namespace VendoreName\ModuleName\Model\Resolver;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Driver\File;
class UploadImage implements ResolverInterface
{
public function __construct(
....................................
Filesystem $fileSystem,
File $fileDriver,
....................................
) {
....................................
$this->fileSystem = $fileSystem;
$this->fileDriver = $fileDriver;
....................................
}
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
) {
//your logic
$this->uploadFile($fileData);
//your logic
}
public function uploadFile($fileData)
{
// convert base64 string to image and save as file on server.
$uploadedFileName = "";
$fileName = '';
if (isset($fileData['name'])) {
$fileName = $fileData['name'];
} else {
$fileName = rand() . time();
}
if (isset($fileData['filecontent'])) {
$mediaPath = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
$originalPath = 'ModuleName/Attachments/';
$mediaFullPath = $mediaPath . $originalPath;
if (!file_exists($mediaFullPath)) {
mkdir($mediaFullPath, 0775, true);
}
/* Check File is exist or not */
$fullFilepath = $mediaFullPath . $fileName;
if ($this->fileDriver->isExists($fullFilepath)) {
$fileName = rand() . time() . $fileName;
}
$fileContent = base64_decode($fileData['filecontent']);
$savedFile = fopen($mediaFullPath . $fileName, "wb");
fwrite($savedFile, $fileContent);
fclose($savedFile);
$uploadedFileName = "/" . $fileName ;
}
return $uploadedFileName;
}
}
Here $fileData is array and with $fileData['filecontent'] = base64 string of file and $fileData['name'] = file name.
Please check the below link and see if it helps:
There are two easy steps to achieve this