Download file does not exist - symfony

I build a csv export using the admin folder. The file is well uploaded into my public folder.
But when I try to download it using the return, I have an error:
The file "/public/exportCSV.csv" does not exist
I can't understand why, I hope you have an idea. Thanks. I'm under Symfony 4.
$admins = $userRepository->findByRole(User::ROLE_ADMIN);
$filename='exportCSV';
$extension='csv';
$request = Request::createFromGlobals();
if($request->query->get('exportCSV')!= null){
$output = fopen($filename.'.'.$extension, 'w');
fputcsv($output, array("Id","Nom","Prénom","Activé","Dernière connexion","Date d'inscription","Url avatar","Email","Username"));
foreach ($admins as $admin){
$id=$admin->getId();
$lastname=$admin->getLastName();
$firstname=$admin->getFirstName();
$activeState=$admin->getActiveState();
if($activeState){
$active='Oui';
}else{
$active='Non';
}
$lastConnectedAt=$admin->getLastConnected();
if($lastConnectedAt==null){
$lastConnected=" ";
}else{
$lastConnected=$lastConnectedAt->format('Y-m-d H:i:s');
}
$createdAt=$admin->getCreatedAt();
if($createdAt==null){
$created=" ";
}else{
$created=$createdAt->format('Y-m-d H:i:s');
}
$urlAvatar=$admin->getUrlAvatar();
$mail=$admin->getEmail();
$username=$admin->getUsername();
$csvLine= array($id,$lastname,$firstname,$active,$lastConnected,$created,$urlAvatar,$mail,$username);
fputcsv($output,$csvLine);
}
return $this->file('/public/'.$filename.'.'.$extension);
}

You must use the correct path to webserver "public" dir. Check https://stackoverflow.com/a/48585423/3497902
In your example, you can do same like ...
$publicDir = $this->getParameter('kernel.project_dir') . '/public/'; # Your controller must extend AbstractController
$output = fopen($publicDir . $filename.'.'.$extension, 'w');

Related

liip imagine_filter in Symfony Controller on non public path

Is there any way to use liip imagine_filter without copying the image source to a public path?
I can not see how resolvers/loaders have to be set up to load images from a non public file location and store them likewise.
I defined a watermark filter with a watermark image placed outside public path - which works without problems. But ONLY applied on images placed IN public path.
I am on Symfony 5 and "liip/imagine-bundle": "^2.6"
I have the same problem as you and i found this solution, of course is a little workaround but it works very well.
So I copy the file from $remoteWatermak into the server. if the $localWatermark is setted I check if the file exist.
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
if($localWatermark){
$filesystem = new Filesystem();
if(!$filesystem->exists($localWatermark)){
$contents = file_get_contents($remoteWatermark,false,
stream_context_create($arrContextOptions)); // get file
file_put_contents($localWatermark , $contents);
}
}else{
$contents = file_get_contents($remoteWatermark,false,
stream_context_create($arrContextOptions)); // get file
$file = "uploads/watermarks/" . uniqid();
file_put_contents($file , $contents);
$localWatermark = $file;
}

Where do you store user uploaded content within a Symfony 4 application?

I have a section within my site where the user can upload their own profile pictures which is stored in the output directory and tracked in the database like so:
$form = $this->createForm(ProfileUpdateForm::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$user = $this->getUser();
$firstname = $form->get('firstname')->getData();
$lastname = $form->get('lastname')->getData();
$picture = $form->get('profilepicture')->getData();
if($picture == null)
{
$user
->setFirstName($firstname)
->setLastName($lastname);
}
else
{
$originalFilename = pathinfo($picture->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = strtolower(str_replace(' ', '', $originalFilename));
$newFilename = $safeFilename.'-'.uniqid().'.'.$picture->guessExtension();
try {
$picture->move(
'build/images/user_profiles/',
$newFilename
);
} catch (FileException $e) {
$this->addFlash("error", "Something happened with the file upload, try again.");
return $this->redirect($request->getUri());
}
// updates the 'picture' property to store the image file name
// instead of its contents
$user
->setProfilePicture($newFilename)
->setFirstName($firstname)
->setLastName($lastname);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash("success", "Your profile was updated!");
return $this->redirectToRoute('account');
}
return $this->render('account/profile.html.twig', [
'profileform' => $form->createView()
]);
That issue I've found is that every time I compile my (local) project, the image is then deleted (because the public/build directory gets built by deleting and creating again).
If I'm not mistaken, isn't that how deployments work too? And if so, is that the right way to upload an image? What's the right way of going about this?
I'm not sure why, but your public/ directory shouldn't be deleted.
If you're using Webpack Encore, then public/build/ content is deleted and created again when you compile assets. But not public/ itself.
For uploads, we create public/upload/ directory.
Then, most of the time, we set some globals, which allow us to save the file name only.
Globals for Twig in config/packages/twig.yaml which "root" will be in your public/ directory
twig:
globals:
app_ul_avatar: '/upload/avatar/'
app_ul_document: '/upload/document/'
And globals for your controllers, repositories, etc in config/services.yaml
parameters:
app_ul_avatar: '%kernel.root_dir%/../public/upload/avatar/'
app_ul_document: '%kernel.root_dir%/../public/upload/document/'
It's handy because, as I just said, you only get to save the file name in the database.
Which mean that, if you got a public/upload/img/ folder, and want to also generates thumbnails, you can then create public/upload/img/thumbnail/ and nothing will change in your database, nor do you have to save an extra path.
Just create a new global app_ul_img_thumbnail, and you're set.
Then all you have to do is call your globals when you need them, and contact with the file name:
In Twig:
{{ app_ul_avatar~dbResult.filename }}
Or in Controller:
$this->getParameter('app_ul_avatar').$dbResult->getFilename();

Laravel-5.3 -Upload-savein database

How store path image with laravel 5.3 ?
if(Input::hasFile('image')){
$file= Input::file('image');
$file->move(public_path().'/',$file->getClientOriginalName());
$blog->title =$file->getClientOriginalName();
}
$blog->save();
Please try it may be working.
$file= Input::file('image');
if(!empty($file)){
$filename = $file->getClientOriginalExtension();
// please identify you upload location
$request->file('image')->move( base_path() . '/public/uploads/', $filename );
$insertdata = array('title'=>$filename);
DB::table('table')->insert($insertdata );
}

PHP - Excel renders PDF without image

I'm developing with the yii2 framework. I need to render some reports which should have some images. Everything is working in my excel file. But in PDF there are no images.
What I have in excel:
What I have in PDF:
My test code looks like this:
public function run($format = self::EXCEL) {
$this->format = $format;
if ($this->format == self::PDF) {
$rendererName = \PHPExcel_Settings::PDF_RENDERER_MPDF;
$rendererLibraryPath = Yii::getAlias('#vendor/mpdf/mpdf/');
if (!\PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibraryPath)) {
throw new BadRequestHttpException('Export pdf fail');
}
$this->headerContentType .= 'pdf';
$this->headerFilename .= date('d_m_Y') . '.pdf';
} elseif ($this->format == self::EXCEL) {
$this->headerContentType .= 'vnd.ms-excel';
$this->headerFilename .= date('d_m_Y') . '.xls';
} else {
throw new Exception('Unknown format for export');
}
$this->objPHPExcel->setActiveSheetIndex(0);
$activeSheet = $this->objPHPExcel->getActiveSheet();
$activeSheet->setTitle('Sample' . date('d_m_Y'));
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setWorksheet($activeSheet);
$activeSheet->getColumnDimension('B')->setWidth(50);
$activeSheet->getRowDimension(2)->setRowHeight(80);
$activeSheet->setCellValue('A2','img -> ');
$activeSheet->setCellValue('B2',' ');
$objDrawing->setCoordinates('B'.2);
$objDrawing->setOffsetX(10)->setOffsetY(10);
$objDrawing->setName('Sample_image');
$objDrawing->setDescription('Sample_image');
$objDrawing->setPath('/home/vladimir/projects/temp/img.jpg');
$objDrawing->setWidth(50)->setHeight(50);
header($this->headerContentType);
header($this->headerFilename);
header('Cache-Control: max-age=0');
$objWriter = \PHPExcel_IOFactory::createWriter($this->objPHPExcel, $this->format);
$objWriter->save('php://output');
exit;
}
In this string:
$objDrawing->setPath('/home/vladimir/projects/temp/img.jpg');
I should write a relative path to "web" directory of my project and also I should have this image into "web" directory.
$objDrawing->setPath('img/img.jpg');
/path_to_project/web/img/img.jpg
I was stuck in CI3 and if you are using CI put the images folder outside of application folder and add path as
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Logo');
$objDrawing->setPath('uploads/organizations/1.jpg');
$objDrawing->setHeight(36);
$objDrawing->setWorksheet($this->excel_reader_writer->getSheetByName($download_section));
The File Structure is
/- application
/- system
/- user_guide
/- uploads

File upload preview image for .doc,.pdf

In drupal when i am uploading a .doc,.pdf files I need to display the preview of the whole document after it get uploaded may i know the answer
I've solved this issue with php, here are the functions that I wrote:
//requires imagemagick which is on most servers
function thumbFromPDF($path, $page=0){
$im = new imagick($path.'['.$page.']');
$im->setImageFormat('png');
$im->writeImage( '/tmp/img.png' );
$im=imagecreatefrompng('/tmp/img.png');
return $im;
}
function thumbFromDoc($path, $page=0){
$cmd='unoconv --server localhost --port 2002 --stdout -f pdf '.$path;//-f could be pdf, txt, or html
$pdf = shell_exec ( $cmd );
$outfilefile='/tmp/pdf.pdf';
if (! $handle = fopen ( $outfilefile, 'w' )) {
die("Cannot open file ($outfilefile)");
return false;
}
// Write $somecontent to our opened file.
if (fwrite ( $handle, $pdf ) === FALSE) {
die("Cannot write to file ($location$file)");
return false;
}
fclose ( $handle );
return thumbFromPDF($outfilefile,$page);
}
Read this article for more information:
http://www.lampdeveloper.co.uk/linux/converting-doc-to-pdf-txt-or-html-using-php-and-linux.html

Resources