Image upload type for Graphql magento2 - file-upload

Is there any way to upload image using graphql without using base64 format in magento2

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;
}
See more: https://magento.stackexchange.com/a/351629/101754

Related

How to validate files with Yii2 getInstancesByName uploaded from API?

I'm working on a mobile app, the Yii2 is used as backend API, the problem that I can not validate the uploaded files, any idea how I can do it?
public static function uploadPicture ($vid) {
$model = new Pictures ();
$model->load(\Yii::$app->getRequest()->getBodyParams(), '');
$model->vid_image = \yii\web\UploadedFile::getInstancesByName('vid_image');
$imageDir = Yii::$app->params[ 'uploadDir' ];
//if ( $model->validate() AND !empty($model->vid_image) ) { //does not work
if ( !empty($model->vid_image) ) {
foreach ( $model->vid_image as $images => $image) {
$model->name = "t_" . time() . "_i_" . uniqid() . '.' . $image->extension;
$model->vid = $vid;
echo $image->hasError;//return empty
//Yii::$app->end();
//if ( $model->save() and $model->validate() ) { // does not work
if(1==1 and $model->validate()){ // $model->validate() always empty!!!
$image->saveAs($imageDir . '/' . $model->name);
Yii::$app->getResponse()->setStatusCode(201);
$id = implode(',', array_values($model->getPrimaryKey(true)));
Yii::info("[pic.21] image: " . $model->name . " uploaded to: " . $imageDir, __METHOD__);
} elseif ( $model->hasErrors() ) {
$response = \Yii::$app->getResponse();
$response->setStatusCode(500);
throw new ServerErrorHttpException('Failed to create the object for unknown reason. [APIx001]');
}
}
}
return $model;
}
The files are uploaded without validation.
Thanks,

timthumb not working after site migration

I just move my site from xfactorapp.com and any new uploaded picture has no thumbnail. Image is on server but thumbnail is not generated.
How can i change that code to make thumbnail visible from new server?
function href_t`imthumb($file, $set = null, $xf = true) {
if (!$set || !$xf) {
$timthumb = webpath_assets('/timthumb.php');
$href = $timthumb . '?src=' . $file;
if (xcount($set) > 0) {
foreach ($set as $k => $v) {
$href .= '&' . $k . '=' . $v;
}
}
return $href;
} else {
$param['w'] = 150;
$param['h'] = 150;
$param['zc'] = 0;
$param['q'] = 90;
if (DEV) {
$app = DEV_PREFIX . APP_VERSION;
} else {
$app = LIVE_PREFIX . APP_VERSION;
}
if (xcount($set) > 0) {
foreach ($set as $k => $v) {
$param[$k] = $v;
}
$file = '/' . $app . $file;
$protocol = 'http';
if (isSSL()) {
$protocol = 'https';
}
return $protocol . '://thumb.xfactorapp.com/tt/' . implode('/', $param) . $file;
}
}
}
wich give me:
<img class="img-responsive" alt="building" src="http://thumb.xfactorapp.com/tt/263/147/2/90/v3/uploads/_lifttec/cms/58529051881f8f0d87ab1401/5947fffeac28b_200-ATJ-Platforma-autoridicatoare-articulata.jpg">
i wish to change code to take thumbnail with parnam properties but from upload not from thumb.xfactorapp.com
Thanks
Just change $xf from true to false $xf = false.
If you changed server, May be GD Library is missing,So Install and Restart Apache then check your file permission.
// To install GD Library
sudo apt-get install php5.6-gd
// To Restart Apache2
sudo /etc/init.d/apache2 restart

Missing file in my email when doing resumable upload with gmail api

I'd like to have some help because I'm a bit lost right now.
I'm trying to send attachment with my email through resumable upload. But when I check my email in my inbox, I don't see any file. So I've probably forgot something.
Here's my code. So if someone see something ^^
$send_data = 'From: <FROM_EMAIL>' . "\n";
$send_data = 'To: <TO_EMAIL>' . "\n";
$send_data = 'Subject: <SUBJECT>' . "\n";
$send_data = '' . "\n";
$send_data = '<MY MESSAGE>' . "\n";
$send_data= rtrim(strtr(base64_encode($send_data), '+/', '-_'), '=');
$msg = new \Google_Service_Gmail_Mesage();
$msg->setRaw($send_data);
$this->client->setDefer(true);
$request = $this->service->users_messages->send('me', $msg, array('uploadType' => 'resumable'));
$chunkSizeBytes = 1 * 1024 * 1024;
$media = new \Google_Http_MediaFileUpload(
$this->client,
$request,
'message/rfc822',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize(TEST_FILE));
$status = false;
$handle = fopen(TEST_FILE, "rb");
$i = 0;
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
$result = false;
if($status != false) {
$result = $status;
}
fclose($handle);
$this->client->setDefer(false);
Thanks
I don't know much about gmail api, but I feel like setRaw() will need you to compose the full email (include the attachment) instead just of "body".

How to get the video upload date with YouTube API V3?

I know how can I get the video duration and views, like that
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=hqepb5hzuB0&key={YOUR-API-KEY}");
$json_data = json_decode($JSON, true);
echo $json_data['items'][0]['statistics']['viewCount'];
But how can I get the video upload date?
$vidkey = "Gsc7_E5HewM" ; //for example
$apikey = "xxxxxxxxxxxxxxxxx" ;
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
//----- duration---
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
// Check if $VidDuration is ISO string so the video is ready
if (is_string($VidDuration)){
//convert duration from ISO to M:S
$date = new DateTime('2000-01-01');
$date->add(new DateInterval($VidDuration));
$vid_durH= $date->format('H') ;
if ($vid_durH=="00") {
$vid_dur= $date->format('i:s') ;
}
else {
$vid_dur= $date->format('H:i:s') ;
}
}
else {
$vid_dur ="error" ;
}
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=$vidkey&key=$apikey");
$json_data = json_decode($JSON, true);
$uploadDate = $json_data['items'][0]['snippet']['publishedAt'];
$uploadDate = strtotime($uploadDate);
$uploadDate= date("F j, Y", $uploadDate);
echo $vid_dur ;

How can I set gzip compression in zend framework website

I am new to zend. I have developed a website using zend framework. Now, I want to set gzip compression in my website. Would you please guide me step wise to implement this.
Thanks in advance.
kamal Arora
There are two methods to gzip output in your website.
Using Webserver.If your webserver is apache you can refer here for a good documentation on how to enable mod_deflate on your server.
Using zend framework. Try the following code which is from this website.
Create a gzip compressed string in your bootstrap file.
Code:
try {
$frontController = Zend_Controller_Front::getInstance();
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
ob_start();
$frontController->dispatch();
$output = gzencode(ob_get_contents(), 9);
ob_end_clean();
header('Content-Encoding: gzip');
echo $output;
} else {
$frontController->dispatch();
}
} catch (Exeption $e) {
if (Zend_Registry::isRegistered('Zend_Log')) {
Zend_Registry::get('Zend_Log')->err($e->getMessage());
}
$message = $e->getMessage() . "\n\n" . $e->getTraceAsString();
/* trigger event */
}
GZIP does not compress images, just the raw HTML/CSS/JS/XML/JSON code from the site being sent to the user.
I made for zend framework 2 (zf2) with your tip
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = str_replace(" ", " ", str_replace("\n", " ", str_replace("\r", " ", str_replace("\t", " ", $content))));
if(#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
{
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}
Honoring the answer of Bruno Pitteli, I think you can compress in the following way:
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'#(?://)?<![CDATA[(.*?)(?://)?]]>#s' //leave CDATA alone
);
$replace = array(
'>',
'<',
'\\1',
"//<![CDATA[n".'1'."n//]]>"
);
$content = preg_replace($search, $replace, $content);
So the full code sample now looks like:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//<![CDATA[n".'1'."n//]]>"), $content);
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}