Unable to write in the \"/var/www/symfony/public/uploads/photos\" - php

I wish to upload files usering a multipart formData in a directory inside my project folder but I receive the error mentioned
The .env file
PHOTO_PATH=/public/uploads/photos
the service.yaml
parameters:
photo_path: '%kernel.project_dir%%env(PHOTO_PATH)%'
the upload function
<?php
namespace App\Service;
use App\DTO\UserRequest;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\String\Slugger\SluggerInterface;
class UserService extends BaseService
{
private SluggerInterface $slugger;
private string $photoPath;
public function __construct(
SluggerInterface $slugger,
ParameterBagInterface $parameters
) {
$this->slugger = $slugger;
$this->photoPath = $parameters->get('photo_path');
}
private function addPhoto(UserRequest $userRequest): string
{
$file = $userRequest->photo;
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = $this->slugger->slug($originalFilename);
$fileName = $safeFilename . '-' . uniqid('', true) . '.' . $file->guessExtension();
$file->move($this->photoPath, $fileName);
return $fileName;
}
}
I receive the following error when i call the function
request.CRITICAL: Uncaught PHP Exception Symfony\Component\HttpFoundation\File\Exception\FileException: "Unable to write in the "/var/www/symfony/public/uploads/photos" directory." at /var/www/symfony/vendor/symfony/http-foundation/File/File.php line 131 {"exception":"[object] (Symfony\\Component\\HttpFoundation\\File\\Exception\\FileException(code: 0): Unable to write in the \"/var/www/symfony/public/uploads/photos\" directory. at /var/www/symfony/vendor/symfony/http-foundation/File/File.php:131)"} []

Related

laravel file upload using custam library

"I'm tring to upload file using custome library in laravel file goes in folder successfully but file isn't upload in database
this is my custom library:-
namespace App\Classes;
use Illuminate\Http\Request;
class Hello
{
static function jai(Request $request)
{
if($request->hasfile('name'))
{
$image=$request->file('name');
$new_image=time().'.'.$image->getClientOriginalName();
$image->move(public_path('image/'),$new_image);
}
}
}
?>
and this is my controller store function :-
Hello::jai($request);
$x=$request->all();
$x['name']=
$j=Hello::jai($request)->new_image;
Cruds::create($x);
The file "[000004].jpg" was not uploaded due to an unknown error.
Hope this will help.
public function upload(Request $request){
if($file = $request->file('file')){
$name = $file->getClientOriginalName();
if($file->move('files',$name)){
$file= new Files();//DB instance modal
$file->url= $name;
$file->save();
return "success";
}
}
You forgot the file extension. See if this help you.
$image = $request->file('your_input_form_file_name');
$image = time() . '_' . $image->getClientOriginalName() . '.' . $file->getClientOriginalExtension();
$image->move(public_path('images/'), $name);

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)
{
...
}

Symfony - failed to open stream only in Command

I'm using Symfony 4.
In my code, I have a function I use in a Controller and in a Command.
public function offlinequiz_check_scanned_page($scannedpage, $colle) {
....
$this->load_stored_image($scannedpage->getFilename(), $scannedpage, $colle);
....
}
public function load_stored_image($file, $scannedpage, $colle) {
....
$pathparts = pathinfo($file);
$filename = $pathparts['filename'] . '.' . $pathparts['extension'];
$imageinfo = getimagesize($file);
....
}
When used in the controller, the function works just fine.
In the Command, I have this error :
Failed to open stream: No such file or directory.
$scannedpage is the same object in both cases.
getFilename() returns an image path : ./uploads/copies/xxx/image_name.jpg.
The upload directory is in /public.
I tried to use Asset Component to get the right path but theses images are uploaded by users and are not managed by Webpack Encore so when I try this :
$package = new Package(new EmptyVersionStrategy());
$this->load_stored_image($package->getUrl($scannedpage->getFilename()), $scannedpage, $colle);
It returns the same as : $scannedpage->getFilename().

Symfony 2.7 access image outside web directory

I read a lot of article about the problem but it seems that there has to be no answer yet to this.
So my project directory is like :
+ uploads_dir
+ symfony_proj
- app
- bin
- src
- vendor
- web
I want to get the image inside the uploads_dir for me to use in my view page
I created twig extension that fetches the roor directory.. but it seems not to read if I put "root_dir"."../../uploads_dir".
Any suggestions ?
Here is the my twig extension part of it:
/**
* #var container
*/
protected $container;
public function __construct(ContainerInterface $container){
$this->container = $container;
}
public function bannerFilter($filename)
{
$file = $this->container->getParameter('kernel.root_dir').'../../uploads_dir'.$filename;
}
I would make the getting of a resource go through a function, this also enables your to do any kind of other checks (like is user logged in, etc).
Create a controller action that processes the request, and then in your twig you can just use a normal path() function.
Some sample code;
parameters.yml
parameters:
upload_destination: '%kernel.root_dir%/../../uploads_dir'
Sample function;
public function getFileAction($file_name)
{
$base_path = $this->container->getParameter('upload_destination');
$full_path = $base_path . '/' . $file_name;
$fs = new FileSystem();
if (!$fs->exists($full_path)) {
throw $this->createNotFoundException();
}
$file_name = basename($full_path);
$mime_type = $this->getMimeType($full_path);
$file = readfile($full_path);
$headers = array(
'Content-Type' => $mime_type,
'Content-Disposition' => 'inline; filename="'.$file_name.'"');
return new Response($file, 200, $headers);
}
protected function getMimeType($file)
{
if ('jpg' === substr($file, -3)) {
$best_guess = 'jpeg';
} else {
$guesser = MimeTypeGuesser::getInstance();
$best_guess = $guesser->guess($file);
}
return $best_guess;
}
In your twig;
<img src="{{ path('whatever_you_called_your_route', {'file_name': 'my_file.jpg'}) }}" />
I got passed this by using /uploads_dir/.
I hopes this helps.

Manipulate Symfony 2 UploadFile object in a unit test

I'm working on a Symfony2 project.
I created a simple TempFile class to manipulate an UploadFile. Here is my constructor :
public function __construct(UploadedFile $file, $destination, $suffix)
{
$this->file = $file;
$this->destination = $destination;
$this->fileId = sprintf('%s_%s', uniqid(), (string) $suffix);
}
And my move method
public function move()
{
$extension = $this->file->guessExtension();
if (!$extension) {
throw new \Exception(__METHOD__ . ' -> Unable to detect extension');
}
$this->tmpFileName = sprintf('%s.%s', $this->fileId, $extension);
$this->file->move($this->destination, $this->tmpFileName);
}
I try to create an UploadFile object in my test and here is what I did :
protected function setUp()
{
$this->file = tempnam(sys_get_temp_dir(), 'upload');
imagepng(imagecreatetruecolor(10, 10), $this->file);
$this->uploadedFile = new UploadedFile($this->file, "test.png");
}
public function testMoveWithAValidUploadedFile()
{
$tempFile = new TempFile($this->uploadedFile, '/tmp', 'tmp');
$tempFile->move();
// Future assertion
}
I have the following error :
Symfony\Component\HttpFoundation\File\Exception\FileException: The file "test.png" was not uploaded due to an unknown error
Any ideas ?
Thx,
Regards
From memory, Symfony2 checks if a file was uploaded as part of the request using is_uploaded_file(). This can be overridden using the test mode of the UploadedFile class. You can also define which PHP upload error code constitutes success.
copy(__DIR__ . '/Fixtures/test.pdf', '/tmp/test.pdf');
new UploadedFile(
'/tmp/test.pdf',
'original.pdf',
null,
null,
UPLOAD_ERR_OK,
true /* test */
)

Categories