i want to validate my file, only .ico files.
Laravel dont include x-icon mime I think, how can i validate it?
$logo = $request->file('logo');
$favicon = $request->file('favicon');
$request->validate([
'logo'=>'image|mimes:png',
'favicon'=>'',
]);
Make a custom validation rule as explained here.
In short:
First do:
php artisan make:rule CheckIfFavicon
Then:
Create the validation code in the created Rules-file.
Try something like:
public function passes($attribute, $value)
{
return $value->getClientOriginalExtension() == 'ico';
}
Then ad it to the validation. Note, that if you make a custom validation class you will have to change the syntax in the $request->validate([...]) from pipe-ing to array.
$request->validate([
'favicon' => [new CheckIfFavicon],
]);
use $file->getClientOriginalExtension() in code if you only want to check file extension
$ext = $file->getClientOriginalExtension();
if($ext == 'ico'){
//uploadfile
}else{
//do something else
}
use this as reference.
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"
]
I have a requirement to upload a document to server, since it is a personal one, they want it to be uploaded outside public folder. I know how to upload a file:
if ($model->load(Yii::$app->request->post())) {
$model->document = UploadedFile::getInstance($model, 'document');
if ($model->upload() !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
But how do I read it since a Url will not be able to access it? I was planning to create an action to get the file but not sure if Yii has something ready for this case?
Yes Yii can send file output, but you still have to create your own action.
Lets assume following code in siteController Specific to image output, You can use same way to output other files.
public function actionImage($image_path) {
Yii::$app->getResponse()->sendFile(Yii::getAlias('#image_uploads') . $image_path);
}
now image src will be something like
<img src="/site/image?image_path=/posts/1.png" /> or equivalent to the real application url routes
So basic function to send file output by Yii2 is
Yii::$app->getResponse()->sendFile();
Located Under
\yii\web\Response.php
I have this part of code:
if ($this->request->isPost() && $this->request->hasFiles()) {
$post = $this->request->getPost();
$file = $this->request->getUploadedFiles();
if ($form->isValid($post)) {
$form->bind((array) $this->request->getPost(), $entity);
$entity->save();
// Do some other stuff
}
}
Is there a way to pass $file to a Phalcon\Forms\Form object?
Or another practice to check if validity of a form that contains both files and text?
To validate Files you must use the FileValidator Class as this example:
$file = new FileValidator([
'maxSize' => '10M',
'messageSize' => _('Your file is huge. Max allowed is 10 Mb'),
'allowedTypes' => ["image/jpeg", "image/png"],
'messageType' => _('File type is not permitted. Try with JPG, GIF, etc..'),
'messageEmpty' => _('Cannot be empty. Please upload a file')
]);
$this->validator->add('filesInputName', $file);
$messages = $this->validator->validate($_FILES);
This is a really old question, but as it affects my current project I share my solution.
Normally, I'm using form classes and validation classes, too. For validating a file upload along with other POST data, I simply combine both payloads:
$entity = new MyCustomModel();
$merged = array_merge($_POST, $_FILES);
if ($form->isValid($merged, $entity)) {
// ...
}
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.