Uploading image issue - laravel

I am trying to upload the image directly to dropbox, and I use croppie too, so
my laravel upload code is:
$user = User::find($request->id_user);
$image = $request->image;
list($type, $image) = explode(';', $image);
list(, $image) = explode(',', $image);
$image = base64_decode($image);
$image_name = $user->rut.'_'.'photo'.'_'. date("d_m_Y") .'.jpg';
$path = public_path('temp_images/'.$image_name);
Storage::disk('dropbox')->putFileAs(
'/intranet_jisparking_pictures/',
$image,
'image.jpg'
);
The problem is that it displays Call to a member function getRealPath() on string
how can I fix it? Thanks!

This is the header for the putFileAs method in the Illuminate\Filesystem\FilesystemAdapter class:
/**
* Store the uploaded file on the disk with a given name.
*
* #param string $path
* #param \Illuminate\Http\File|\Illuminate\Http\UploadedFile $file
* #param string $name
* #param array $options
* #return string|false
*/
public function putFileAs($path, $file, $name, $options = [])
It looks like the second argument is supposed to be a File or UploadedFile, but you are giving it the result of base64_decode which is a string.
One way to solve this is by creating an instance of UploadedFile yourself in a temporary file. See this answer for an example.

Related

How to queue upload to s3 using Laravel?

I'm dispatching a job to queue my video file, the files are being stored on s3.
Everything is working except if I upload a video file for example that's 20mb, when I look in my bucket it says the file is 120b. So this makes me think that I'm uploading the path and filename as a string instead of the file object.
And for some reason, when I try getting the file using the Storage::get() or File::get() and dd the result, it shows a bunch or random and crazy characters.
It seems like I can only get these weird characters, or a string, I can't get the file object for some reason.
In my controller I'm also storing it in the public disk (I will delete the file later in my Jobs/UploadVideos.php file).
CandidateProfileController.php:
$candidateProfile = new CandidateProfile();
$candidateProfile->disk = config('site.upload_disk');
// Video One
if($file = $request->file('video_one')) {
$file_path = $file->getPathname();
$name = time() . $file->getClientOriginalName();
$name = preg_replace('/\s+/', '-', $name);
$file->storePubliclyAs('videos', $name, 'public');
$candidateProfile->video_one = $name;
}
if($candidateProfile->save()) {
// dispatch a job to handle the image manipulation
$this->dispatch(new UploadVideos($candidateProfile));
return response()->json($candidateProfile, 200);
} else {
return response()->json([
'message' => 'Some error occurred, please try again.',
'status' => 500
], 500);
}
Jobs/UploadVideos.php:
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $candidateprofile;
public $timeout = 120;
public $tries = 5;
/**
* Create a new job instance.
*
* #param CandidateProfile $candidateProfile
*/
public function __construct(CandidateProfile $candidateProfile)
{
$this->candidateprofile = $candidateProfile;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$disk = $this->candidateprofile->disk;
$filename = $this->candidateprofile->video_one;
$original_file = storage_path() . '/videos/' . $filename;
try {
// Video One
Storage::disk($disk)
->put('videos/'.$filename, $original_file, 'public');
// Update the database record with successful flag
$this->candidateprofile->update([
'upload_successful' => true
]);
} catch(\Exception $e){
Log::error($e->getMessage());
}
}
File Storage docs
The 2nd parameter for put() should be the contents of the file not the path to the file. Also, unless you've updated the public disk in your config/filesystem.php, the video isn't going to be stored in storage_path() . '/videos/...'.
To get this to work you should just need to update your Job code:
$filename = 'videos/' . $this->candidateprofile->video_one;
Storage::disk($this->candidateprofile->disk)
->put($filename, Storage::disk('public')->get($filename), 'public');
$this->candidateprofile->update([
'upload_successful' => true,
]);
Also, wrapping your code in a try/catch will mean that the Job won't retry as it will technically never fail.

I get different random values for the same file

I am trying to store photo in DB, and I use the below way to generate a random file name and store it in the DB.
$path = $request->file('profile_photo')->store('public/profiles');
$profile = ltrim($path,"public/profiles/");
However, sometimes I get different values in
DB
and in my folder
I am using laravel 6.
ltrim(), rtrim(), trim() remove by character mask, not full string.
$profile = ltrim($path,"public/profiles/");
It means remove all "p", "u", "b", "l", "i", "c", "/", etc. from the left side of $path.
If you want to get filename without path, you could use basename() function.
$profile = basename($path);
Alright take a look at this src/Illuminate/Http/UploadedFile.php
/**
* Store the uploaded file on a filesystem disk.
*
* #param string $path
* #param array|string $options
* #return string|false
*/
public function store($path, $options = [])
{
return $this->storeAs($path, $this->hashName(), $this->parseOptions($options));
}
/**
* Store the uploaded file on a filesystem disk.
*
* #param string $path
* #param string $name
* #param array|string $options
* #return string|false
*/
public function storeAs($path, $name, $options = [])
{
$options = $this->parseOptions($options);
$disk = Arr::pull($options, 'disk');
return Container::getInstance()->make(FilesystemFactory::class)->disk($disk)->putFileAs(
$path, $this, $name, $options
);
}
You can do this to get ride of the collision and confusion
// cache the file
$file = $request->file('profile_photo');
// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'profile-photo-' . time() . '.' . $file->getClientOriginalExtension();
// save to public/photos as the new $filename
$path = $file->store('public/photos', $filename);
dd($path); // Check if you get the correct file path or not

How do i redirect to an external url with headers?

How i have an application which is sitting on A server and i would like to allow user to get to another application which is in B server with a header of the user information. I have done some tries but i m not getting the header in B server. How can i achieve that ya?
Bellow are the codes which i have tried:-
return redirect()->away($apiUrl)->header('x-api-token', $token);
and
$client = new Client();
$request = $client->request('get', $apiUrl, [
'headers' => [
'x-api-user-token' => $userToken
]
]);
Is there a way for me to redirect to an external url with a header?
You might want to try the helper method provided by Laravel and it works like a charm for me.
return redirect('http://external.url/', 302, [
'custom-header' => 'custom value'
])
If you want to look at the source code please refer
/vendor/laravel/framework/src/Illuminate/Foundation/Helpers.php
/**
* Get an instance of the redirector.
*
* #param string|null $to
* #param int $status
* #param array $headers
* #param bool $secure
* #return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
*/
function redirect($to = null, $status = 302, $headers = [], $secure = null)
{
if (is_null($to)) {
return app('redirect');
}
return app('redirect')->to($to, $status, $headers, $secure);
}

Typo3 fluid image from external resource

is it possible to resize images in fluid from external resource. I have an extension with datas from SOAP. So image URL looks like http://www.example.com/url/of/image/imagename.jpg.
<f:image src="{data.url.image}" with="300" />
is not working.
Maybe an own ViewHelper which fetch the external image and save it to an temporary folder could help. After this you can modify the image.
Something like this (not tested):
<?php
namespace MyNamespaece\MyExt\ViewHelpers;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\ViewHelpers\ImageViewHelper;
use TYPO3\CMS\Core\Resource\FileInterface;
use TYPO3\CMS\Extbase\Domain\Model\AbstractFileFolder;
class ExternalImageViewHelper extends ImageViewHelper
{
const UPLOAD_DIRECTORY = 'externalImages';
const TEMP_PREFIX = 'MyExt';
/**
* ResourceFactory
*
* #var \TYPO3\CMS\Core\Resource\ResourceFactory
* #inject
*/
protected $resourceFactory = null;
/**
* Resizes a given image (if required) and renders the respective img tag
*
* #see https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Image/
*
* #param string $src a path to a file, a combined FAL identifier or an uid (integer). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead
* #param string $width width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* #param string $height height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.
* #param integer $minWidth minimum width of the image
* #param integer $minHeight minimum height of the image
* #param integer $maxWidth maximum width of the image
* #param integer $maxHeight maximum height of the image
* #param boolean $treatIdAsReference given src argument is a sys_file_reference record
* #param FileInterface|AbstractFileFolder $image a FAL object
*
* #return string
* #throws \Exception
* #throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException
* #throws \TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException
* #throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
*/
public function render($src = null, $width = null, $height = null, $minWidth = null, $minHeight = null, $maxWidth = null, $maxHeight = null, $treatIdAsReference = false, $image = null)
{
if (filter_var($src, FILTER_VALIDATE_URL)) {
$storage = $this->resourceFactory->getDefaultStorage();
if (!$storage->hasFolder(self::UPLOAD_DIRECTORY)) {
$storage->createFolder(self::UPLOAD_DIRECTORY);
}
$externalFile = GeneralUtility::getUrl($src);
if ($externalFile) {
$tempFileName = tempnam(sys_get_temp_dir(), self::TEMP_PREFIX);
$handle = fopen($tempFileName, "w");
fwrite($handle, $externalFile);
fclose($handle);
$uploadFolder = $storage->getFolder(self::UPLOAD_DIRECTORY);
$file = $uploadFolder->addFile($tempFileName, basename(basename($src)), 'changeName');
$src = $file->getPublicUrl();
unlink($tempFileName);
} else {
throw new \Exception(sprintf('External URL % cannot accessed.', $src), 1473233519);
}
}
return parent::render($src, $width, $height, $minWidth, $minHeight, $maxWidth, $maxHeight, $treatIdAsReference, $image);
}
}
Please Note: This ViewHelper has no check if the image is allready fetched! So an check should be integrated. Otherwise this viewhelper fetch the image at each page refresh!
As mentioned in the comments I want to clarify that this ViewHelper should not be used in any production environment. It should only demonstrate how the way to such an viewhelper could be. Compiled templates are not supported. Also no needed check if the file already exists is implemented. Your hosting environment could be flooded with downloads and can break you file quota!
The short answer is: This is not possible.
The long answer is: Of course it is possible if you fetch the image first. There are various ways to do it:
At runtime as rpflamm suggested by using a ViewHelper
Do it in your controller/service when you fetch the SOAP call. IMO this would be the best way. Persist then the image and use the local path
If the images you fetch are not that big, of course a resizing via CSS is also an option
Working Version with cropping-feature for TYPO3 10.4 LTS:
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*
* Example: <xyz:externalImage filename="OPTINAL_FILENAME" src="EXTERNAL_URL" width="480c" height="270c" title="YOUR TITLE" alt="YOUR ALT" class="YOUR-CLASS" />
*/
namespace YourNamespaece\YourExtension\ViewHelpers;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Service\ImageService;
use TYPO3\CMS\Fluid\Core\Widget\Exception;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper;
class ExternalImageViewHelper extends AbstractTagBasedViewHelper {
/**
* #var string
*/
protected $tagName = 'img';
/**
* #var \TYPO3\CMS\Extbase\Service\ImageService
*/
protected $imageService;
/**
* #param \TYPO3\CMS\Extbase\Service\ImageService $imageService
*/
public function injectImageService(ImageService $imageService)
{
$this->imageService = $imageService;
}
const UPLOAD_DIRECTORY = 'externalImages';
const TEMP_PREFIX = 'diakonie_baukasten';
/**
* ResourceFactory
*
* #var ResourceFactory
* #TYPO3\CMS\Extbase\Annotation\Inject
*/
protected ResourceFactory $resourceFactory;
/**
* Initialize arguments.
*/
public function initializeArguments()
{
parent::initializeArguments();
$this->registerUniversalTagAttributes();
$this->registerTagAttribute('alt', 'string', 'Specifies an alternate text for an image', false);
$this->registerArgument('filename', 'string', 'Override filename for local file.', false, '');
$this->registerArgument('src', 'string', 'a path to a file, a combined FAL identifier or an uid (int). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead', true, '');
$this->registerArgument('width', 'string', 'width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.');
$this->registerArgument('height', 'string', 'height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.');
$this->registerArgument('minWidth', 'int', 'minimum width of the image');
$this->registerArgument('minHeight', 'int', 'minimum height of the image');
$this->registerArgument('maxWidth', 'int', 'maximum width of the image');
$this->registerArgument('maxHeight', 'int', 'maximum height of the image');
$this->registerArgument('absolute', 'bool', 'Force absolute URL', false, false);
}
/**
* Resizes a given image (if required) and renders the respective img tag
*
* #see https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Image/
*
* #return string Rendered tag
* #throws \Exception
*/
public function render()
{
$src = (string)$this->arguments['src'];
$filename = (string)$this->arguments['filename'];
if ($src === '') {
throw new Exception('You must either specify a string src', 1382284106);
}
// A URL was given as src, this is kept as is, and we can only scale
if ($src !== '' && preg_match('/^(https?:)?\/\//', $src)) {
if (filter_var($src, FILTER_VALIDATE_URL)) {
$storage = $this->resourceFactory->getDefaultStorage();
if (!$storage->hasFolder(self::UPLOAD_DIRECTORY)) {
$storage->createFolder(self::UPLOAD_DIRECTORY);
}
$externalFile = GeneralUtility::getUrl($src);
if ($externalFile) {
$tempFileName = tempnam(sys_get_temp_dir(), self::TEMP_PREFIX);
$handle = fopen($tempFileName, "w");
fwrite($handle, $externalFile);
fclose($handle);
if ($filename !== '') {
$fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $src);
$fileExtension = str_replace($fileNameNoExtension,"", $src);
$src = $filename.$fileExtension;
}
$uploadFolder = $storage->getFolder(self::UPLOAD_DIRECTORY);
$file = $uploadFolder->addFile($tempFileName, basename(basename($src)), 'replace');
$src = $file->getPublicUrl();
unlink($tempFileName);
$image = $this->imageService->getImage($src, null, false);
$processingInstructions = [
'width' => $this->arguments['width'],
'height' => $this->arguments['height'],
'minWidth' => $this->arguments['minWidth'],
'minHeight' => $this->arguments['minHeight'],
'maxWidth' => $this->arguments['maxWidth'],
'maxHeight' => $this->arguments['maxHeight'],
'crop' => null,
];
$processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
$imageUri = $this->imageService->getImageUri($processedImage, $this->arguments['absolute']);
$this->tag->addAttribute('src', $imageUri);
$this->tag->addAttribute('width', $processedImage->getProperty('width'));
$this->tag->addAttribute('height', $processedImage->getProperty('height'));
// The alt-attribute is mandatory to have valid html-code, therefore add it even if it is empty
if (empty($this->arguments['alt'])) {
$this->tag->addAttribute('alt', $image->hasProperty('alternative') ? $image->getProperty('alternative') : '');
}
// Add title-attribute from property if not already set and the property is not an empty string
$title = (string)($image->hasProperty('title') ? $image->getProperty('title') : '');
if (empty($this->arguments['title']) && $title !== '') {
$this->tag->addAttribute('title', $title);
}
return $this->tag->render();
} else {
throw new \Exception(sprintf('External URL % cannot accessed.', $src), 1473233519);
}
}
}
}
}

How to print collection mysql query in magento

Let's say I have a collection like:
$products = Mage::getModel('catalog/product')
->getCollection()
...
->load();
How do I print the actual MySQL code that gets executed?
You can always view your sql query at a certain point by echoing getSelect as shown:
$products = Mage::getModel('catalog/product')
->getCollection();
echo $products->getSelect();
To change query parameters you want to check out methods like:
$products->addAttributeToSelect('someattribute');
$products->addAttributeToFilter('someattribute', array('eq'=>'1'));
You can print collection using below code:
We can print query of collection using getSelect()->__toString()
$products = Mage::getModel(‘catalog/product’)
->addAttributeToFilter(‘status’, array(‘eq’ => 1));
echo $products->getSelect()->__toString();
Have you seen http://kuldipchudasama.wordpress.com/2012/07/16/magento-print-query-of-collection/?
This works well.
Most other answers here say that $products->getSelect() will do it - this is fine if all you're going to do with it is echo, but in fact getSelect() doesn't just return a string, it returns a Varien_Db_Select object.
Invoking echo on that object automatically triggers its __toString() method, so you just get the SQL string, but try passing it to Mage::log() and you'll get a lot more than you expected.
If you just want to log the SQL, you can use:
Mage::log($products->getSelect()->__toString());
Or how about using the object's own:
$products->printLogQuery(false, true); // don't echo, do log
printLogQuery is defined in lib/Varien/Data/Collection/Db.php.
You can print
$products->getSelect()->assemble();
I work with collections every day. This is without a doubt the correct way.
echo $collection->getSelectSql(true);
If you simple set the first parameter of ->load() to true, like so:
$products = Mage::getModel('catalog/product')
->getCollection()
...
->load(true);
In Magento 2:-
namespace <Company>\<Module>\Block\Adminhtml\Tab\Log;
class Grid
extends \Magento\Backend\Block\Widget\Grid\Extended
{
protected $_collectionFactory;
/**
* Constructor
*
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Backend\Helper\Data $backendHelper
* #param \<Company>\<Module>\Model\ResourceModel\Log\CollectionFactory $collectionFactory
* #param Psr\Log\LoggerInterface $logger
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\<Company>\<Module>\Model\ResourceModel\Log\CollectionFactory $collectionFactory,
\Psr\Log\LoggerInterface $logger,
array $data = []
) {
$this->_logger = $logger;
$this->_collectionFactory = $collectionFactory;
parent::__construct($context, $backendHelper, $data);
}
/**
* {#inheritdoc}
*/
protected function _prepareCollection()
{
$collection = $this->_collectionFactory->create();
$this->_logger->info($collection->getSelect()->__toString());
$this->setCollection($collection);
return parent::_prepareCollection();
}
}
And remember that the collection factory is a magic class that can attaches to every class as Magento 1 wasn't complicated enough.
Step 1-
$result_colletion = print_r($collection->getSelect());
Mage::log($$result_colletion, null, custom_collection.log,true);
Step 2-
After that Login into magento admin section and enable to log setting . Please see below .
System > Configuration > Developer > Log Settings
Step 3-
After that see the log file custom_collection.log in var/log/ folder .
Try following code.
$products = Mage::getModel('catalog/product')
->getCollection();
echo $products->getSelect();

Resources