Zend Framework 3: create download link for generated file - php

I'm writing an app that lets the user upload an Excel file. It checks the file for errors, then, if no errors are found, it uploads the contents to a database. If it does find errors, the cells containing errors are colored red, then the file is saved. I then want to create a download link to this file so the user can check where they made mistakes.
The problem is that I am not sure how to create this link and where to store the file. I modify the file like this:
foreach ($badCells as $bcell) {
$sheet->getStyle($bcell)->applyFromArray(array(
'fill' => array(
'type' => \PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'FF4444')
)
));
}
And then save it with
$objWriter->save($dldir . $formData['upload']['name']);
$dldir is created with
$dldir = "/download/";
if (file_exists($dldir)) {
if (!is_dir($dldir)) {
unlink($dldir);
mkdir($dldir);
}
} else {
if(!is_dir($dldir)) {
mkdir($dldir);
}
}
Is this even the right way to do this? Can I store the files in any old folder or do they have go somewhere specific? How do I create the link to the specific file in the view for the user and make it accessible so they can download it?

I may be wrong .
For file upload i use this library Gargron/fileupload
The function bellow help to upload file to a specific folder and return full link of the file. You can save the link in DB
function uploadFile ($file){
$validator = new \FileUpload\Validator\Simple('5M');
$pathresolver = new \FileUpload\PathResolver\Simple($_SERVER['DOCUMENT_ROOT'].'/upload_folder');
$filesystem = new \FileUpload\FileSystem\Simple();
$fileupload = new \FileUpload\FileUpload(file, $_SERVER);
$fileupload->setPathResolver($pathresolver);
$fileupload->setFileSystem($filesystem);
$fileupload->addValidator($validator);
$md5Generator = new \FileUpload\FileNameGenerator\MD5 (true);
$fileupload->setFileNameGenerator($md5Generator);
list($files) = $fileupload->processAll();
foreach($files as $file){
if ($file->completed) {
return $_SERVER['DOCUMENT_ROOT'].'/upload_folder/'.$file->getFileName()) ;
}
}
}

Thanks for the help, I managed to figure it out over the weekend. Here's how I did
it:
$filename = join(DIRECTORY_SEPARATOR, array($dldir, $formData['upload']['name']));
$objWriter->save(str_replace(__FILE__,$filename,__FILE__));
This is how I save the file, using DIRECTORY_SEPARATOR so it will work correctly on both Windows and Linux.
return $this->redirect()->toRoute('import', ['action' => 'reject'],['query' => ['q' => 'file', 'name' => $filename]]);
In the controller, I redirect the route to the correct action and pass the file name on to it via a query URL.
public function rejectAction()
{
$filename = $this->getRequest()->getQuery('name', null);
return new ViewModel(array('filename' => $filename));
}
There, I obtain said file name through getRequest()->getQuery() and pass it on to the viewmodel.
Right-click here and choose 'Save As' to download your file.
And finally, this is how it shows the link in reject.phtml.
Downloading only works with right click and save as, I suspect I will have to write some sort of file handler to make ZF produce the correct headers for a normal left click download.

Related

Multiple type Post CRUD

i want to create form with php that have multiple part and type of data. Such as:
Input Text (name,title, description,etc)
Input image (header_img)
Input Multiple image (slider)
The point is i want to create a lot of data include upload file in one page using php.
In post method, i try standard logic, upload one by one of image with if else logic, with a lot of if else logic and different name and insert it in each field of database (one field in one field database) huft....
if($_FILES['imghead']['size']!=0){
// run upload method
}
And for edit , i try it manually, same as post method, using if else for each field. for example:
if($_FILES['imghead']['size']!=0){
// run upload method
}
if($_FILES['slider1']['size']!=0){
// run upload method
}
if($_FILES['slider2']['size']!=0){
// run upload method
}
if($_FILES['slider3']['size']!=0){
// run upload method
}
// etc
But the problem is, i think my method is not really good, its not effective and i must write a lot of code and check them one bu one with if else logic.
My Question:
Do you know how to optimize my logic to real simple code? specially CRUD.
i have try grocery crud but i need more feature like multiple images upload
There is a way to implement multiple images upload with grocerycrud, in the controller you need to asign a different name method to every upload field that you need and then just copy paste the main method in the Grocery_CRUD.php file and change the name to the same that you assigned
Controller code:
$crud->set_field_upload('file1','assets/uploads');
$crud->set_another_field_upload('file2','assets/uploads');
This is the code that you need to copy, (route:htdocs\app_name\application\libraries\Grocery_CRUD.php)
public function set_field_upload($field_name, $upload_dir = '')
{
$upload_dir = !empty($upload_dir) && substr($upload_dir,-1,1) == '/'
? substr($upload_dir,0,-1)
: $upload_dir;
$upload_dir = !empty($upload_dir) ? $upload_dir : 'assets/uploads/files';
/** Check if the upload Url folder exists. If not then throw an exception **/
if (!is_dir(FCPATH.$upload_dir)) {
throw new Exception("It seems that the folder \"".FCPATH.$upload_dir."\" for the field name
\"".$field_name."\" doesn't exists. Please create the folder and try again.");
}
$this->upload_fields[$field_name] = (object) array(
'field_name' => $field_name,
'upload_path' => $upload_dir,
'encrypted_field_name' => $this->_unique_field_name($field_name));
return $this;
}
Just paste it below and change the function name with the same name assigned in your controller:
public function set_another_field_upload($field_name, $upload_dir = '')
{
$upload_dir = !empty($upload_dir) && substr($upload_dir,-1,1) == '/'
? substr($upload_dir,0,-1)
: $upload_dir;
$upload_dir = !empty($upload_dir) ? $upload_dir : 'assets/uploads/files';
/** Check if the upload Url folder exists. If not then throw an exception **/
if (!is_dir(FCPATH.$upload_dir)) {
throw new Exception("It seems that the folder \"".FCPATH.$upload_dir."\" for the field name
\"".$field_name."\" doesn't exists. Please create the folder and try again.");
}
$this->upload_fields[$field_name] = (object) array(
'field_name' => $field_name,
'upload_path' => $upload_dir,
'encrypted_field_name' => $this->_unique_field_name($field_name));
return $this;
}

php, data not updating after form post in zend?

this might be a bit of a novice question and here is my situation:
i have a upload form for uploading images. and in my editAction i do:
if ($request->isPost()) {
if (isset($_POST['upload_picture']) && $formImageUpload->isValid($_POST)) {
//here i will add the picture name to my database and save the file to the disk.
}
}
$picVal = $this->getmainPic(); // here i do a simple fetch all and get the picture that was just uploaded
$this->view->imagepath = $picVal;
what happens is that the newly uploaded picture doesn't show. I checked the database and the dick and the file is there.
im thinking the problem might be the order of the requests or something similar.
any ideas?
edit: another thing is that in order to make the new image come up i have to do a SHIFT+F5 and not only press the browser refresh button
edit2: more code
i first call the upload to disk function then if that returns success addthe file to the database
$x = $this->uploadToDiskMulty($talentFolderPath, $filename)
if($x == 'success'){
$model->create($data);
}
the upload function
public function uploadToDiskMulty($talentFolderPath, $filename)
{
// create the transfer adapter
// note that setDestiation is deprecated, instead use the Rename filter
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addFilter('Rename', array(
'target' => $filename,
'overwrite' => true
));
// try to receive one file
if ($adapter->receive($talentFolderPath)) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
If the picture only appears when you do SHIFT+F5 that means it's a caching problem. Your browser doesn't fetch the image when you upload it. Do you use the same file name?

How to upload a file in a directory containing the record ID on Symfony

I have a file upload form in the frontend.
At the moment, when a new record is created, the file is uploaded to
%sf_data_dir%/files/
but due to some business logic I need the file to be uploaded to
%sf_data_dir%/files/%record_id%/
Therefore the uploaded file should be saved AFTER the record is created.
How can I achieve that?
If you use file upload, your form certainly make use of the sfValidatorFile (if not, that's wrong):
$this->validatorSchema['image'] = new sfValidatorFile(array(
'required' => true,
'mime_types' => 'web_images',
));
This validator return a sfValidatedFile instance that can be saved anywhere you want (it's safer than move_uploaded_file, there is checks on the directory, filename...).
In your action (or in the form, as you want/need), you can now do this:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind(
$request->getParameter($form->getName()),
$request->getFiles($form->getName())
);
if ($form->isValid())
{
$job = $form->save();
// Saving the file to filesystem
$file = $form->getValue('my_upload_field');
$file->save('/path/to/save/'.$job->getId().'/myimage.'.$file->getExtension());
$this->redirect('job_show', $job);
}
}
Don't hesitate to open sfValidatedFile to see how it work.

How to do file uploads with PHP and the Zend Framework?

I am using Zend Framework 1.9.6. I think I've got it pretty much figured out except for the end. This is what I have so far:
Form:
<?php
class Default_Form_UploadFile extends Zend_Form
{
public function init()
{
$this->setAttrib('enctype', 'multipart/form-data');
$this->setMethod('post');
$description = new Zend_Form_Element_Text('description');
$description->setLabel('Description')
->setRequired(true)
->addValidator('NotEmpty');
$this->addElement($description);
$file = new Zend_Form_Element_File('file');
$file->setLabel('File to upload:')
->setRequired(true)
->addValidator('NotEmpty')
->addValidator('Count', false, 1);
$this->addElement($file);
$this->addElement('submit', 'submit', array(
'label' => 'Upload',
'ignore' => true
));
}
}
Controller:
public function uploadfileAction()
{
$form = new Default_Form_UploadFile();
$form->setAction($this->view->url());
$request = $this->getRequest();
if (!$request->isPost()) {
$this->view->form = $form;
return;
}
if (!$form->isValid($request->getPost())) {
$this->view->form = $form;
return;
}
try {
$form->file->receive();
//upload complete!
//...what now?
$location = $form->file->getFileName();
var_dump($form->file->getFileInfo());
} catch (Exception $exception) {
//error uploading file
$this->view->form = $form;
}
}
Now what do I do with the file? It has been uploaded to my /tmp directory by default. Obviously that's not where I want to keep it. I want users of my application to be able to download it. So, I'm thinking that means I need to move the uploaded file to the public directory of my application and store the file name in the database so I can display it as a url.
Or set this as the upload directory in the first place (though I was running into errors while trying to do that earlier).
Have you worked with uploaded files before? What is the next step I should take?
Solution:
I decided to put the uploaded files into data/uploads (which is a sym link to a directory outside of my application, in order to make it accessible to all versions of my application).
# /public/index.php
# Define path to uploads directory
defined('APPLICATION_UPLOADS_DIR')
|| define('APPLICATION_UPLOADS_DIR', realpath(dirname(__FILE__) . '/../data/uploads'));
# /application/forms/UploadFile.php
# Set the file destination on the element in the form
$file = new Zend_Form_Element_File('file');
$file->setDestination(APPLICATION_UPLOADS_DIR);
# /application/controllers/MyController.php
# After the form has been validated...
# Rename the file to something unique so it cannot be overwritten with a file of the same name
$originalFilename = pathinfo($form->file->getFileName());
$newFilename = 'file-' . uniqid() . '.' . $originalFilename['extension'];
$form->file->addFilter('Rename', $newFilename);
try {
$form->file->receive();
//upload complete!
# Save a display filename (the original) and the actual filename, so it can be retrieved later
$file = new Default_Model_File();
$file->setDisplayFilename($originalFilename['basename'])
->setActualFilename($newFilename)
->setMimeType($form->file->getMimeType())
->setDescription($form->description->getValue());
$file->save();
} catch (Exception $e) {
//error
}
By default, files are uploaded to the system temporary directory, which means you'll to either :
use move_uploaded_file to move the files somewhere else,
or configure the directory to which Zend Framework should move the files ; your form element should have a setDestination method that can be used for that.
For the second point, there is an example in the manual :
$element = new Zend_Form_Element_File('foo');
$element->setLabel('Upload an image:')
->setDestination('/var/www/upload')
->setValueDisabled(true);
(But read that page : there are other usefull informations)
If you were to move the file to a public directory, anyone would be able to send a link to that file to anyone else and you have no control over who has access to the file.
Instead, you could store the file in the DB as a longblob and then use the Zend Framework to provide users access the file through a controller/action. This would let you wrap your own authentication and user permission logic around access to the files.
You'll need to get the file from the /tmp directory in order to save it to the db:
// I think you get the file name and path like this:
$data = $form->getValues(); // this makes it so you don't have to call receive()
$fileName = $data->file->tmp_name; // includes path
$file = file_get_contents($fileName);
// now save it to the database. you can get the mime type and other
// data about the file from $data->file. Debug or dump $data to see
// what else is in there
Your action in the controller for viewing would have your authorization logic and then load the row from the db:
// is user allowed to continue?
if (!AuthenticationUtil::isAllowed()) {
$this->_redirect("/error");
}
// load from db
$fileRow = FileUtil::getFileFromDb($id); // don't know what your db implementation is
$this->view->fileName = $fileRow->name;
$this->view->fileNameSuffix = $fileRow->suffix;
$this->view->fileMimeType = $fileRow->mime_type;
$this->view->file = $fileRow->file;
Then in the view:
<?php
header("Content-Disposition: attachment; filename=".$this->fileName.".".$this->fileNameSuffix);
header('Content-type: ".$this->fileMimeType."');
echo $this->file;
?>
$this->setAction('/example/upload')->setEnctype('multipart/form-data');
$photo = new Zend_Form_Element_File('photo');
$photo->setLabel('Photo:')->setDestination(APPLICATION_PATH ."/../public/tmp/upload");
$this->addElement($photo);

Zend Framework: image upload

I want to upload an image with Zend Framework version 1.9.6. The uploading itself works fine, but I want a couple of other things as well ... and I'm completely stuck.
Error messages for failing to upload an image won't show up.
If a user doesn't enter all the required fields but has uploaded an image then I want to display the uploaded image in my form. Either as an image or as a link to the image. Just some form of feedback to the user.
I want to use Zend_ Validate_ File_ IsImage. But it doesn't seem to do anything.
And lastly; is there some automatic renaming functionality?
All ideas and suggestions are very welcome. I've been struggling for two days now.
These are simplified code snippets:
myform.ini
method = "post"
elements.title.type = "text"
elements.title.options.label = "Title"
elements.title.options.attribs.size = 40
elements.title.options.required = true
elements.image.type = "file"
elements.image.options.label = "Image"
elements.image.options.validators.isimage.validator = "IsImage"
elements.submit.type = "submit"
elements.submit.options.label = "Save"
TestController
<?php
class Admin_TestController extends Zend_Controller_Action
{
public function testAction ()
{
$config = new Zend_Config_Ini(MY_SECRET_PATH . 'myform.ini');
$f = new Zend_Form($config);
if ($this->_request->isPost())
{
$data = $this->_request->getPost();
$imageElement = $f->getElement('image');
$imageElement->receive();
//$imageElement->getValue();
if ($f->isValid($data))
{
//save data
$this->_redirect('/admin');
}
else
{
$f->populate($data);
}
}
$this->view->form = $f;
}
}
?>
My view just echo's the 'form' variable.
First, put this at the start of your script:
error_reporting(E_ALL);//this should show all php errors
I think the error messages are missing from the form because you re-populate the form before you display it. I think that wipes out any error messages. To fix that, remove this part:
else
{
$f->populate($data);
}
To show the uploaded image in the form, just add a div to your view template, like this:
<div style="float:right"><?=$this->image?></div>
If the image uploaded ok, then populate $view->image with an img tag.
As for automatic re-naming, no, it's not built in, but it's very easy. I'll show you how below.
Here's how I handle my image uploads:
$form = new Zend_Form();
$form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
$image = new Zend_Form_Element_File('image');
$image->setLabel('Upload an image:')
->setDestination($config->paths->upload)
->setRequired(true)
->setMaxFileSize(10240000) // limits the filesize on the client side
->setDescription('Click Browse and click on the image file you would like to upload');
$image->addValidator('Count', false, 1); // ensure only 1 file
$image->addValidator('Size', false, 10240000); // limit to 10 meg
$image->addValidator('Extension', false, 'jpg,jpeg,png,gif');// only JPEG, PNG, and GIFs
$form->addElement($image);
$this->view->form = $form;
if($this->getRequest()->isPost())
{
if(!$form->isValid($this->getRequest()->getParams()))
{
return $this->render('add');
}
if(!$form->image->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
return $this->render('add');
}
if($form->image->isUploaded())
{
$values = $form->getValues();
$source = $form->image->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'someNameYouInvent';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '/www/yoursite/images/'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="/images/'.$new_image_name.'" />';
$form->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
First, have a look at the Quick Start tutorial. Note how it has an ErrorController.php that will display error messages for you. Also note how the application.ini has these lines to cause PHP to emit error messages, but make sure you're in the "development" environment to see them (which is set in public/.htaccess).
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
Second, ZF has a renaming filter for file uploads:
$upload_elt = new Zend_Form_Element_File('upload');
$upload_elt
->setRequired(true)
->setLabel('Select the file to upload:')
->setDestination($uploadDir)
->addValidator('Count', false, 1) // ensure only 1 file
->addValidator('Size', false, 2097152) // limit to 2MB
->addValidator('Extension', false, 'doc,txt')
->addValidator('MimeType', false,
array('application/msword',
'text/plain'))
->addFilter('Rename', implode('_',
array($this->_user_id,
$this->_upload_category,
date('YmdHis'))))
->addValidator('NotExists', false, $uploadDir)
;
Some of the interesting things above:
mark the upload as required (which your .ini doesn't seem to do)
put all the uploads in a special directory
limit file size and acceptable mime types
rename upload to myuser_category_timestamp
don't overwrite an existing file (unlikely, given our timestamp scheme, but let's make sure anyway)
So, the above goes in your form. In the controller/action that receives the upload, you could do this:
$original_filename = $form->upload->getFileName(null, false);
if ($form->upload->receive()) {
$model->saveUpload(
$this->_identity, $form->upload->getFileName(null, false),
$original_filename
);
}
Note how we capture the $original_filename (if you need it) before doing receive(). After we receive(), we do getFileName() to get the thing that the rename filter picked as the new filename.
Finally, in the model->saveUpload method you could store whatever stuff to your database.
Make sure your view also outputs any error messages that you generate in the controller: loading errors, field validation, file validation. Renaming would be your job, as would other post processing such as by image-magick convert.
When following lo_fye's listing I experienced problems with custom decorators.
I do not have the default File Decorator set and got the following exception:
Warning: Exception caught by form: No file decorator found... unable to render file element Stack Trace:
The Answer to this is that one of your decrators must implement the empty interface Zend_Form_Decorator_Marker_File_Interface
Also sometimes it happens to bug when using an ajax request. Try it without an ajax request and don't forget the multipart form.

Categories