Turn a files content into an UploadedFile - php

I have a file saved in my application whose content I would like to create a laravel UploadedFile with.
$content = file_get_contents(storage_path('app/Imports/example.csv'));
// returns Illuminate\Http\UploadedFile;
$uploadedFile = $this->someMethodToMakeLaravelUploadedFile($content);
How can I achieve this?

You can make a new Uploadedfile
use Illuminate\Http\UploadedFile;
return new UploadedFile($path, $name);
In your case
$uploadedFile = new UploadedFile(storage_path('app/Imports/example.csv')), 'example.csv')

Related

how to delete a file or a photo from the folder when deleting it from database?

hi i'm try to delete image from folder but i'm getting this error message
Class 'App\Http\Controllers\File' not found
when i dd() the image path it look like this : "C:\xampp\htdocs\blog\public\/images/1544525527.jpg"
here is my delete code:
$post = Post::find($id);
$file= $post->image;
$destinationPath = public_path('/images');
$filename = $destinationPath.'/'.$file;
File::delete($filename);
and i upload image like this:
if ($request->hasFile('image')) {
$image = $request->file('image');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$post->image = url('/public/images/').'/'.$name;
}
Try importing the class at the top of your controller file:
use Illuminate\Support\Facades\File;
there are two solutions for this, first you can import the class by add this code in controller file
use Illuminate\Support\Facades\File;
or alternatively you can use the full path class in your code, so your code should be like this,
$post = Post::find($id);
$file= $post->image;
$destinationPath = public_path('/images');
$filename = $destinationPath.'/'.$file;
//fullpath class
\Illuminate\Support\Facades\File::delete($filename);
direct delete from your directory please try this will use in your controller
use File;
that also use in your controllers function
$update = tablename::where('id',$request->input('uid'))->where('status',1)->first();
if ($request->hasFile('cover'))
{
File::delete(public_path().$update->pu_cover_photo);
}

Error uploading images using Slim framework

I am trying to create an API endpoint using Slim that allows people upload images. I am however having issues as I keep getting this error message,
"Argument 2 passed to moveUploadedFile() must be an instance of
UploadedFile, instance of Slim\Http\UploadedFile given"
This is what I am doing:
$directory = __DIR__.'/uploads';
function moveUploadedFile($directory, UploadedFile $uploadedFile)
{
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
// see http://php.net/manual/en/function.random-bytes.php
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
$files = $request->getUploadedFiles();
$uploadedFile = $files['photo'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
}
Please how I solve this?
The error tells you that PHP is looking for class UploadedFile in current namespace because you add typehint for it. Since there is no class named UploadedFile in your current namespace, hence the error.
Add use clause for example
use Slim\Http\UploadedFile;
...
function moveUploadedFile($directory, UploadedFile $uploadedFile)
{
...
}
or typehint full class name
function moveUploadedFile($directory, Slim\Http\UploadedFile $uploadedFile)
{
...
}

How to know uploaded file size on symfony 3?

i use FOSRestbundle to manage my api. I implemented a action to upload a file on symfony that it's working well. But the problem is that i need to obtain the file size... My action get the file on this way:
$uploadedfile = $request->files->get('file');
this obtains an array of all files that i upload.
Reading the doc of symfony for the $uploadedfile object, there is a method called:
getClientSize()
so i used and always return 0:
$fileSize = $uploadedfile->getClientSize();
There are another way to get the file size? I'm doing something wrong?
Thanks a lot.
how about the solution here?
http://symfony.com/doc/current/reference/constraints/File.html#maxsize
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* #Assert\File(
* maxSize = "1024k",
* mimeTypes = {"application/pdf", "application/x-pdf"},
* mimeTypesMessage = "Please upload a valid PDF"
* )
*/
protected $bioFile;
}
you might have to create an entity for that, if you have not done so.
So if you want to use validation in your controller, you would do something like
// ...
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Author;
// ...
public function authorAction()
{
$author = new Author();
// ... do something to the $author object
$validator = $this->get('validator');
$errors = $validator->validate($author);
if (count($errors) > 0) {
$errorsString = (string) $errors;
return new Response($errorsString);
}
return new Response('The author is valid! Yes!');
}
you can test it, by uploading a file larger than the maxsize, set in your given Author Entity in that case you would get the message "Please upload a valid PDF"
Have you successfully moved the file into the intended folder? if you have, you can just call a native php function filesize().
http://php.net/manual/en/function.filesize.php

manually creating an Symfony UploadedFile

I'm facing following problem and can't seem to figure this one out.
I wrote an API endpoint accepting a POST with binary data (header: content-type:image/jpeg).
I know i can read out the raw string with file_get_content('php://input') or Laravel's $request->getContent().
PHP also has a function createimagefromstring($string) which also seems to read the string in correctly.
What i'd like to do is create an UploadedFile from this raw data , so that I can handle it with already written functions.
Is this possible?
Thank you in advance
I think I found it... Still curious if there are improvements that can be made..
$imgRaw = imagecreatefromstring( $request->getContent() );
if ($imgRaw !== false) {
imagejpeg($imgRaw, storage_path().'/tmp/tmp.jpg',100);
imagedestroy($imgRaw);
$file = new UploadedFile( storage_path().'/tmp/tmp.jpg', 'tmp.jpg', 'image/jpeg',null,null,true);
// DO STUFF WITH THE UploadedFile
}
You can try to use base64 encoding. Symfony have some nice stuff for this.
Your code will be smthng like this:
$base64Content = $request->request->get('base64Content'); // this is your post data
$yourFile = new UploadedBase64EncodedFile(new Base64EncodedFile($base64Content)); // this is an instance of UploadedFile
Hope it helps!
As per Laravel 8
Just follow the constructor:
* #param string $path The full temporary path to the file
* #param string $originalName The original file name of the uploaded file
* #param string|null $mimeType The type of the file as provided by PHP; null defaults to application/octet-stream
* #param int|null $error The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants); null defaults to UPLOAD_ERR_OK
* #param bool $test Whether the test mode is active
$file = new UploadedFile(
$pathIncludingFilename,
$fileName,
'image/jpeg',
null,
false
);
There is no need to manually create it, Symfony parses received $_FILES array for you. Http Request object has a FileBag property called $files with a get() method which returns an UploadedFile instance.
/** #var UploadedFile $file */
$file = $request->files->get('user-pictures-upload')[0];
$cmd = new UploadPictureCmd($file, $this->getUser()->getId());
Here is the example of generating images files using fzaninotto/faker in Symfony 4 Fixtures
class FileFixtures extends Fixture
{
private $faker;
private $parameterBag;
public function __construct(ParameterBagInterface $parameterBag)
{
$this->faker = Factory::create();
$this->parameterBag = $parameterBag;
}
public function load(ObjectManager $manager)
{
$tempFixturesPath = $this->parameterBag->get('kernel.project_dir') . '/tmp';
if (!file_exists($tempFixturesPath)) {
mkdir($tempFixturesPath);
}
$fileName = $this->faker->image($tempFixturesPath, 640, 480, 'cats', false, true);
$file = new UploadedFile($tempFixturesPath . '/' . $fileName, $fileName, 'image/jpeg', null, null, true);
//do something with $file
}
}
If it counts for anything, this is how I did it in Laravel 5.4. In my case, I wanted to be able to easily resize an image and be able to do something like this.
request()->file('image')->resize(250, 250)->store('path/to/storage');
This is what I did to the UploadedFile class.
Illuminate\Http\UploadedFile.php ~this file ships with the Laravel framework
public function resize($w, $h) {
$image = Intervention::make($this)->fit($w, $h)->save($this->getPathname());
$filesize = filesize($this->getPathname());
return new static(
$this->getPathname(),
$this->getClientOriginalName(),
$this->getClientMimeType(),
$filesize,
null,
false
);
}
Using Intervention, I resized the image that is stored in the /tmp/ folder when files are uploaded and then I saved it in the same place. Now all I do after that is create an instance of UploadedFile so that I can keep using Laravel's methods on request()->file('image'). Hope this helps.

Trying to get property of non-object when accessing from called function

I'm using yii framework but I think this is related to PHP
In my controller, I have the following code
$model = new Events;
$model->type_id = $type_id;
$checkFileUpload = checkFileUpload($model);
the function checkFileUpload is a custom function which contains
function checkFileUpload($model)
{
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if($uploadedFile->error == 0)
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
...
I got the error get property of non-object in $uploadedFile->error.
I've tried to use reference to the model instead, but it is deprecated and does not work for me.
If I use the code of the called function (checkFileUpload) within the controller code, it works fine. I suspect that object is not passed in a correct way.
Any help?
This is because your call to CUploadedFile::getInstance returns null and not the instance you desired.
Null is returned if no file is uploaded for the specified model attribute.
— Yii Documentation
It seems like your file was not correctly uploaded. I am not a Yii Framework user, but the documentation states:
The file should be uploaded using CHtml::activeFileField.
— Yii Documentation
So you should verify that the file was actually correctly uploaded with the proper method from the Yii Framework.
PS: Objects are always passed by reference.
$model = new Events;
$type_id=$model->type_id;
$checkFileUpload = checkFileUpload($model);
function checkFileUpload($model)
{
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if(!isset($uploadedFile->getHasError()))
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
The problem occurred because at the time when you are using $uploadedFile->error,the value of $uploadedFile is null.
The following line is not giving you the desired value
$uploadedFile = CUploadedFile::getInstance($model, 'image');
Which means no file has been uploaded.
Try CVarDumper::dump($_FILES,10,true);
This will tell you whether the problem is with the UPLOADING OF THE FILE or GETTING THE DETAILS OF THE UPLOADED FILE
you cant access the private property $_error $uploadedFile->_error if you are trying to. you must call $uploadedFile->getError() in your code. Also $uploadedFile will return null if no file uploaded so you must take care of that as well.
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if(!empty($uploadedFile) && !$uploadedFile->getHasError())
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
will work for you.

Categories