I'm trying to have a simple form with a file upload, but it isn;t working. when I check form_state both in the validate and in the submit callbacks, the file value is missing. also check $_FILES and there's nothing.
here is the code I'm using in _form:
$form['file'] = array(
'#type' => 'file',
'#title' => 'Photo',
);
this is what i'm doing in submit:
$validators = array();
$file = file_save_upload('file', $validators, '/sites/default/files');
file_set_status($file, FILE_STATUS_PERMANENT);
krumo ($file);
You need specify $form['#attributes'] = array('enctype' => 'multipart/form-data'); apart from your other fields to make it working. See here for details.
Related
I use the plugin 'blueimp jquery fileupload' to upload files in Javascript (that part I got it right) and then I have to handle the uploads on the server side using an uploadhandler affiliated to the plugin (UploadHandler.php).
Working in Symfony, I managed to create a service based on this php script and it works in my controller (the files are uploaded in the default repository, yet on my page I get the error message 'upload failed' and I don't know why but it's not a big problem I guess), but the thing is :
I would like to custom the repository path to upload the files based on the user id, and since I call the uploadhandler file as a service, I don't know how to override the options using the construct function, as I would be able to with a basic call in php.
Here's my code :
public function uploadFiles(Request $request)
{
$uploadhandler = $this->container->get('extranetcontratbundle.uploadhandler');
$response = $uploadhandler->response;
$files = $response['files'];
return new JsonResponse($files);
}
In the options of UploadHandler.php there is :
$this->options = array(
'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/',
'upload_url' => $this->get_full_url().'/files/',
'input_stream' => 'php://input',
'user_dirs' => false,
'mkdir_mode' => 0755,
'param_name' => 'files',
...blabla
And I would like to override the options in a similar way as I would in 'normal' php :
$tmpImagesDir = JPATH_ROOT . 'tmp' . $userId .;
$tmpUrl = 'tmp/' . $userId . '/' . '/';
$uploadOptions = array('upload_dir' => $tmpImagesDir, 'upload_url' => $tmpUrl);
$uploadHandler = new UploadHandler($uploadOptions);
But to do that I would have to write "require_once(blabla)" and I would have created the service for nothing. If I understood it right, that's not the way to do it in Symfony. Is there a way ?
Thank you for reading, please help.
I tried to upload video file using kartik FileInput widget.
When I use the same to field to upload image it works very fine but problem arise once I turn to video.
This is activeForm field in my view file
<?= $form->field($model, 'myFile')->widget(FileInput::classname(),
[
'pluginOptions' => [
'showUpload' => false,
'browseLabel' => 'Insert File',
'removeLabel' => '',
'mainClass' => 'input-group-md'
],
'options' => ['accept' => 'image/*, video/*']
])
?>
And I use below code to save file in the disk
if(isset($model->myFile)){
$file = UploadedFile::getInstance($model,'myFile');
if(!empty($file)){
$path=Yii::$app->basePath . '/web/uploads/';
$filetmp = explode(".", $file->name);
$extension = end($filetmp);
$encryptName = Yii::$app->security->generateRandomString().".{$extension}";
$file->saveAs($path.$encryptName);
}
} else
{
throw new \yii\web\HttpException(500, 'File not saved try again');
}
When I upload form to the controller it return
Unable to verify your data submission (400 bad request error)**
I have already tried to modify php.ini as
max_input_time = -1,
upload_max_filesize = 100M,
post_max_size = 100M
And also when I when I tried to set enableCsrfValidation = false; in that controller action request post contain no data.
I don't know what exactly is the problem.
I have a Symfony2 entity called MyUploadedFiles and a form type MyUploadedFilesType with the name myuploadedfiles. This form type builds a form with a single field file. This field should not be blank and the rest of the data in the entity is generated, once a user uploads a file. Now, I want to run a functional test for my controller that handles the upload. But I I always get the error file should not be blank.
This is the code in my myUploadTest method:
$filepath = __DIR__.'/test_file.xml';
$xmlfile = new UploadedFile(
$filepath,
'foo.xml',
'text/xml',
\filesize($filepath)
);
$client->request(
'POST',
'/path/to/xml_upload',
array(),
array('myuploadedfiles[file]' => $xmlfile)
);
$response = $client->getResponse();
$this->assertEquals(Codes::HTTP_CREATED, $response->getStatusCode());
The controller looks like:
$form->bind($request);
if ($form->isValid()) { ... }
If I render the form with a twig template and try to upload something everything works fine. So probably the error is somewhere in the test code.
Thanks for the help!
I use this code:
# Select the file from the filesystem
# Path of the file to send
$filepath = __DIR__.'/test_file.xml';
$xmlfile = new UploadedFile(
$filepath,
'foo.xml',
'text/xml',
\filesize($filepath)
);
# Select the form (adapt it for your needs)
$form = $crawler->filter('input[type=submit]...')->form();
# Put the file in the upload field
$form['myuploadedfiles[file]']->upload($xmlfile);
# Send it
$crawler = $this->client->submit($form);
# Check that the file has been successfully sent
# (in my case the filename is displayed in a <a> link so I check
# that it appears on the page)
$this->assertEquals(
1,
$crawler->filter('a:contains("foo.xml")')->count()
);
Apparently this is a common problem but I have not been able to figure out how to get a Zend Captcha Image to show up, it will create the image and it will create the hidden element but the image tag never shows up, does anyone have a solution??
Here is the code that doesn't work:
<?php
class Application_Form_Contact extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setAction('/contact/')->setMethod('post');
$element = new Zend_Form_Element_Text('name');
$element->setLabel('Name:')
->setRequired(true)
->addFilter('HtmlEntities');
$this->addElement($element);
$element = new Zend_Form_Element_Text('phone');
$element->setLabel('Phone:')
->setRequired(true)
->addFilter('HtmlEntities');
$this->addElement($element);
$element = new Zend_Form_Element_Text('email');
$element->setLabel('Email:')
->setRequired(true)
->addValidator('EmailAddress', true)
->addFilter('StripTags')
->addFilter('HtmlEntities')
->addFilter('StringToLower')
->addFilter('StringTrim');
$this->addElement($element);
$comments = $this->createElement('textarea', 'comments')
->setLabel('Comments:')
->setRequired(true)
->setOptions(array('style'=>'width:95%;'))
->addFilter('StripTags')
->addFilter('HtmlEntities')
->addFilter('StringTrim');
$this->addElement($comments);
$captcha= new Zend_Form_Element_Captcha('captcha', array(
'id'=>'captchas',
'title'=>'Security Check.',
'captcha' => array(
'captcha' => 'Image',
'required' => true,
'font'=> PUBLIC_PATH . '/verdana.ttf',
'wordlen'=>'4',
'width'=>'80',
'height'=>'50',
'ImgAlign'=>'left',
'imgdir'=> PUBLIC_PATH . '/images/captcha/',
'DotNoiseLevel'=>'0',
'LineNoiseLevel'=>'0',
'Expiration'=>'1000',
'fontsize'=>'16'
)));
$this->addElement($captcha);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Send');
$this->addElement($submit);
}
}
I've only got two ideas that might help:
Check to make sure your GD extension is enabled in php.
It requires the GD extension compiled with TrueType or Freetype support. Currently, the Zend_Captcha_Image adapter can only generate PNG images.
you may want to specify the imgUrl =>
setImgUrl($imgUrl) and getImgUrl() allow you to specify the relative path to a CAPTCHA image to use for HTML markup. The default is "/images/captcha/".
also just for information you don't need to set the element as required as the captcha is always required.
As noted, the captcha adapter itself acts as a validator for the element. Additionally, the NotEmpty validator is not used, and the element is marked as required. In most cases, you should need to do nothing else to have a captcha present in your form.
Try to edit your captcha down to bare bones
$captcha = new Zend_Form_Element_Captcha('Captcha', array(
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 6,
'timeout' => 300,
'width' => 300,
'height' => 100,
'imgUrl' => '/captcha',
'imgDir' => APPLICATION_PATH . '/../public/captcha',
'font' => APPLICATION_PATH . '/../public/fonts/LiberationSansRegular.ttf')));
just get anything to work then add back what you need 'till you find the problem. I suspect you have a problem with one of your paths.
Start with the APPLICATION_PATH constant then change to PUBLIC_PATH if you feel it's better.
check your file permissions; I had to give group write access before the image would write.
I cannot understand how ->isuploaded() works. I am suppose to upload six images to display on my index page. Now the problem is, in my update function, if I upload only one or two image $upload->isUploaded() returns a false value, but if I decide to update all six of them it returns a true value. How do I deal with this problem? Am i missing out something here?
Here is my zend file transfer upload
$upload = new Zend_File_Transfer();
$upload->addValidator('Count', false, array('min' =>1, 'max' => 6))
->addValidator('Size', false, array('max' => '1Mb'))
->addValidator('ImageSize', false, array('minwidth' => 50,
'maxwidth' => 1000,
'minheight' => 50,
'maxheight' => 1000));
if ($upload->isUploaded()) $hasImage = true;
By default Zend guess all uploaded files are invalid even if just one of submitted form file fields was empty.
Zend docs are suggest to override this behavior by calling isValid() method before receive().
So I'm not sure if suggest best solution, but it works for me:
$upload = new Zend_File_Transfer();
$upload->setDestination( 'some your destination' );
if( $adapter->isValid( 'your form file field name' ) ){
$adapter->receive( 'your form file field name' );
}
And so on with every file field name. Wrap in foreach if needed.
Use isValid() instead.
if ($upload->isValid()) {
// success!
} else {
// failure!
}
Once you know your upload passed the validators, then start processing the images.