Upload an image using Zend Framework? - php

I want to upload an image in Zend-framework.
In Application_Form_Test.php I write following code....
uploadImage = new Zend_Form_Element_File('uploadImage');
$uploadImage->setLabel("Upload Image ")
->setRequired(true)
->addValidator('Extension', false, 'jpeg,png')
->getValidator('Extension')->setMessage('This file type is not supportted.');
In the testAction() I write following code.....
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addValidator('Size', false, 52428800, 'image');
$upload->setDestination('uploads');
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
if ($upload->isValid($file)) {
$upload->receive($file);
}
}
Code is running successfully But I am not getting that image to the destination folder?
What may be the problem....?
Please help me.....
Thanks in advance....

I don't think that the getFileInfo() method is supposed to actually execute the file upload. I believe that in your controller action, you have to either call the getValues() method on the form object, or call the receiveFile() method on the form element.
See http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.file for the documentation examples.

An additional note: if you look in Zend_Form_Element_File->receive(), you will see that isValid() is called, so there's no need to clutter your controller with it. Here's what I do:
if ($upload->receive()) {
if ($upload->getFileName() && !file_exists($upload->getFileName())) {
throw new Exception('The upload should have worked, but somehow did not!');
}
} else {
throw new Exception(implode(PHP_EOL, $upload->getErrors()) . implode(PHP_EOL, $upload->getErrorMessages()));
}

Related

Call to a member function on a non-object getting errors

I tried so many time but this code is not working. I don't know why. It is a image upload form. This code worked for another form but here it's getting an error: Call to a member function isValid() on a non-object
$file = array('dest_img' => Input::file('dest_img'));
// checking file is valid.
if (Input::file('dest_img')->isValid()) {
$destinationPath = 'uploads'; // upload path
$extension = Input::file('dest_img')->getClientOriginalExtension(); // getting image extension
$fileName = $s.'.'.$extension;
$imgPath= $destinationPath.'/'.$fileName;
//return $imgPath;
// renameing image
Input::file('dest_img')->move($destinationPath, $fileName); // uploading file to given path
// sending back with message
//Session::flash('success', 'Upload successfully');
//return Redirect::to('tblaze_admin/bannerAdd');
$data=array(
'dest_title' =>$input['dest_title'],
'dest_desc' =>$input['dest_desc'],
'dest_img' =>$imgPath,
);
//$result=Cms::where('cms_id',$cms_id)->update($data);
$result=Destination::where('dest_id',$dest_id)->update($data);
if($result >0)
{
\Session::flash('flash_message','Destination Updated Successfull!!');
}
else
{
\Session::flash('flash_error_message','Destination Updation Failed!!');
}
}
I'm stuck at this code; please give a solution
Have you added enctype="multipart/form-data" to your <form> tag? Or if you're using the Form builder, 'files' => true?
Input::file('dest_img') is not an object. You might have not loaded the classes that define Input. Check that laravel is bootstrapped correctly.

validating and save an uploaded ajax image in Yii

I need to send an image to server via an ajax request and it gets through just fine
and in my controller I can just use $_FILES["image"] to do stuff to it.
But I need to validate the image before I save it.
And in the Yii this can be achieved by doing something like this
$file = CUploadedFile::getInstance($model,'image');
if($model->validated(array('image'))){
$model->image->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user_thumb/' . $model->username.'.'.$model->photo->extensionName);
}
But the problem is I don't have a $model, all I have is $_FILES["image"], now what should I put instead of the $model???
is there any other way where I can validate and save files without creating a model and just by Using $_FILES["image"]?
thanks for this awesome community... :)
Exists many ways how you can do upload. I want offer to you one of them.
1.You need to create model for your images.
class Image extends CActiveRecord {
//method where need to specify validation rules
public function rules()
{
return [
['filename', 'length', 'max' => 40],
//other rules
];
}
//this function allow to upload file
public function doUpload($insName)
{
$file = CUploadedFile::getInstanceByName($insName);
if ($file) {
$file->saveAs(Yii::getPathOfAlias('webroot').'/upload/user_thumb/'.$this->filename.$file->getExtensionName());
} else {
$this->addError('Please, select at least one file'); // for example
}
}
}
2.Now, need to create controller, where you will do all actions.
class ImageController extends CController {
public function actionUpload()
{
$model = new Image();
if (Yii::app()->request->getPost('upload')) {
$model->filename = 'set filename';
$insName = 'image'; //if you try to upload from $_FILES['image']
if ($model->validate() && $model->doUpload($insName)) {
//upload is successful
} else {
//do something with errors
$errors = $model->getErrors();
}
}
}
}
Creating a model might be overkill in some instances.
The $_FILE supervariable is part of the HTTP mechanism.
You can handle the copy by using the native PHP function move_uploaded_file()
$fileName = "/uploads/".myimage.jpg";
unlink($fileName);
move_uploaded_file($_FILES['Filedata']['tmp_name'], $fileName);
However, you lose the niceties of using a library that provides additional functionality and checks (eg file type and file size limitations).

jQuery File Upload 'undefined' image url

I'm using a plugin called jQuery file upload to upload images to a page. Currently it uploads with the original image name as the file name (IMG_1234). I need a specific format for the image name on the server (eg 1.123456.jpg)
I found this PHP code that works for changing the image name:
class CustomUploadHandler extends UploadHandler
{
protected function trim_file_name($name, $type) {
$name = time()."_1";
$name = parent::trim_file_name($name, $type);
return $name;
}
}
When I upload an image, it is named correctly, but the link for the image preview is undefined. This prevents me from deleting the image via the plugin.
The variable data.url is undefined... If I go back to the original code that doesn't rename the image, everything works fine.
Has anyone had any experience with this plugin that could help? Thanks!
EDIT:
I've found part of the problem at least...the function to return the download link (which is also used for deletion) is giving the original file name, not the updated one. I am really new to PHP classes, so I'm not sure where the variable originates and how to fix it. I'd really appreciate any help I can get!
Here's the PHP code for that function:
protected function get_download_url($file_name, $version = null, $direct = false) {
if (!$direct && $this->options['download_via_php']) {
$url = $this->options['script_url']
.$this->get_query_separator($this->options['script_url'])
.'file='.rawurlencode($file_name);
// The `$file_name` variable is the original image name (`IMG_1234`), and not the renamed file.
if ($version) {
$url .= '&version='.rawurlencode($version);
}
return $url.'&download=1';
}
if (empty($version)) {
$version_path = '';
} else {
$version_url = #$this->options['image_versions'][$version]['upload_url'];
if ($version_url) {
return $version_url.$this->get_user_path().rawurlencode($file_name);
}
$version_path = rawurlencode($version).'/';
}
return $this->options['upload_url'].$this->get_user_path()
.$version_path.rawurlencode($file_name);
}
EDIT 2: I think it has something to do with 'param_name' => 'files', in the options. Anyone know what that does?
Fixed it by editing the trim_file_name function inside UploadHandler.php instead of extending the class in index.php.

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 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);

Categories