validating and save an uploaded ajax image in Yii - php

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

Related

how to add uploded file name in to database using yii

I want to upload file with yii, I kinda did it. When I hit the submit button the file is saved in the folder where it should be. However, I want to add the filename to the database as well. How can I achieve this?
this is my controller :
public function actionUpload()
{
$model = new TourImage();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance($model, ‘imageFile’);
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render(‘upload’, [
‘model’ => $model
]);
}
You can extract the name of the original file from UploadedFile.getInstance() and assign it to the attribute of your model (This is normally done in your model "TourImage", in the upload method that you have had to implement).
Therefore if you have this in your controller action:
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
Then, in the upload() method of your TourImage model:
$this->your_model_attribute = $this->imageFile->name; // The original name of the file being uploaded
Change your_model_attributes to the attribute of your model where you want to save the file name.
Look at the public properties of the UploadedFile object:
https://www.yiiframework.com/doc/api/2.0/yii-web-uploadedfile

PHP - How to pass class to another class method

Im trying to pass the verot image editing class to a custom class that I created, but it doesnt seem to work, it doesnt do anything when I try to run it. How do I pass the verot image class to my class?
//Edit.php
//Now I run my class
$process = new ProcessEventLogo();
$process->editEventLogo($event_id,$file_ext,$savepath,new upload(''));
Here is my custom class. I thought by running upload('') to this method, Im passing a copy of the verot upload class that I can access in my custom class method. But when I run it, it doesnt even get past the $mainimg->uploaded path. In fact $mainimg = $fileupload->upload($savefile); returns NULL when I var_dump it. What am I doing wrong?
class ProcessEventLogo {
public function editEventLogo($eventid,$fext,$url,$savepath,$fileupload)
{
//We generate the file name to save this image to
$savefile = $savepath .'event_' .$eventid .'.' .$fext;
//We check to see if the event image is there
$mainimg = $fileupload->upload($savefile);
//We now resize the image
if($mainimg->uploaded)
{
$mainimg->file_overwrite = TRUE;
$mainimg->image_ratio_crop = TRUE;
$mainimg->image_resize = TRUE;
$mainimg->image_x = 50;
$mainimg->image_y = 50;
$mainimg->process($savefile);
if($mainimg->processed)
{
echo $mainimg->error;
}
}
}
It appears this worked, can someone verify this is the proper way of doing this? So instead of this line:
//We check to see if the event image is there
$mainimg = $fileupload->upload($savefile);
This worked.
//We check to see if the event image is there
$mainimg = new $fileupload($savefile);
#mr.void Right, so how else would I pass this class to my custom class
method? Just seems like this is the wrong way
I think writing a little Factory is the right way for this:
class uploadFac {
public function getUploadInstance($file)
{
return new upload($file)
}
}
And use it like this:
$uplFac = new uploadFac();
$process = new ProcessEventLogo();
$process->editEventLogo($event_id,$file_ext,$savepath,$uplFac);
and in the method:
public function editEventLogo($eventid,$fext,$url,$savepath,$uplFac)
{
//We generate the file name to save this image to
$savefile = $savepath .'event_' .$eventid .'.' .$fext;
$mainimg = $uplFac->getUploadInstance($savefile);

Laravel php controller for pdf

I am wondering what to write in my laravel controller to allow me work with a pdf document posted from the front end by an AJAX request. I have found code online to check if an image is uploaded, but anyone have an idea what I need to do if it's a pdf document.
Please see my code below.
public function postUpload() {
$file = Input::file('image');
do something here.....
}
An example from documentation:
public function postUpload(Request $request) {
if ($request->hasFile('file')) {
$file = $request->file('file');
do something here.....
}
}
To check if file is PDF, use validation rules, like:
$rules = [
"file" => "mimes:pdf"
]

Getting an extension of an uploaded file in yii2

I'm trying to get an extension of a file during upload but I get an error that path info requires a string:
I have tried:
$path_parts = pathinfo($_FILES['evidence']['name']);
echo $path_parts['extension'];
How can extract file extension, for example jpeg, doc, pdf, etc.
If you are using yii2 kartik file input you can get the instance of yii\web\uploadedFile this way to:
$file = UploadedFile::getInstanceByName('evidence'); // Get File Object byName
// Then you can get extension by this:
$file->getExtension()
If you want to validate file as well then you can use FileValidator using adhoc role:
$validator = new FileValidator(['extensions' => ['png','jpg']]);
if( $validator->validate($file, $errors) ) {
// Validation success now you can save file using $file->saveAs method
} else {
// ToDO with error: print_r($errors);
}
It's better not use $_FILES directly in Yii2 since framework provides abstraction with a class yii\web\UploadedFile. There is also separate page in guide describing working with uploaded files.
There is an example with model.
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
As you can see, extension is extracted using extension property ($this->imageFile->extension).
There are more info about form settings, handling in controller, uploading multiple files. All this can be found by the link mentioned above.

Upload an image using Zend Framework?

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

Categories