Get selected file from media module - drupal-7

I am trying to get the file that the user has selected from the media selector from the media module in Drupal 7.
My form contains the selector and can upload and select a file successfully, but unable to get the name of the file that has been chosen.
My form for the selector:
$form['file'] = array(
'#type' => 'media',
'#title' => t('Screenshot'),
'#description' => t('Upload an image of the feature (Optional)'),
),
);
I need to get the details of the selected file (e.g. name, directory)

Try to use hook_submit to check the file name.
Suposing the file field in your form is named "file":
function your_form_submit($form, &$form_state) {
$file=$form_state['values']['file'];
// do something...
file_save($file);
You can use form_vaidate as well, i don't know exactly what you want to do with the file name...

Related

TYPO3 TCA Overriding exists file

I have an issue like this with TYPO3.
I have an object, this object has file attribute, this field named "pdf"
In the TCA this field I defined like this:
'pdf' => array(
'exclude' => 1,
'label' => 'LLL:EXT:locations/Resources/Private/Language/locallang_db.xlf:tx_locations_domain_model_location.pdf',
'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig(
'files', array(
'appearance' => array(
'createNewRelationLinkTitle' => 'LLL:EXT:cms/locallang_ttc.xlf:images.addFileReference',
),
'size' => 1,
'minitems' => 0,
'maxitems' => 1,
), $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
)
),
And now I can upload a file or image for this field, but there are some things does not good:
I want to allow PDF files only
After upload one file, if I upload another file, is said that "The existing files be overwritten" but old file never be overwritten.
The new one is also not uploaded.
What I need for this case: If I upload a new file, the old file will be overwritten by the new one.
Thanks for your help.
Since you pass in $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] you are currently allowing all kind of image-like file extensions. This is the point where you might want to use 'pdf' instead.
If you want to overwrite files, you'll need to to this in the File module of TYPO3. If you want to put a different file in your relation, you can remove the current one and add another one. The first file won't be deleted automatically but your record will have a relation to the new file.

Symfony2 simple file upload edit without entity

Please help me out here because I can't belive my eyes.
I refuse to use some 3rd party plugin for file uploads, and refuse to creat a separate entity for a file/document. I just want simple file upload that I would do in Zend/Laravel and so on.
I have a invoice table with the last collumb name "attachment", I want to store here its sanitized name (eg: 123421_filename.jpg ), the addition form and upload went well.
code here:
//AddAction
$file=$form['attachment']->getData();
$fileName=$file->getClientOriginalName();
$sanitizedFilename=rand(1, 99999).'_'.$fileName;
$dir='files/'.$userId.'/';
$file->move($dir, $sanitizedFilename);
...
$invoice->setAttachment($sanitizedFilename);
$em = $this->getDoctrine()->getManager();
$em->persist($invoice);
First problem I have and don't know how to solve is using the edit form.. I have a formbuilder
$builder->add('attachment', 'file',array('data_class'=>null))
Because I don't have a "Object" for my file and because in my invoice table I store the name as a string, I get an error here and I need to force the data_class => null .. which is bad, because if I edit a Invoice in the frontend for the upload field I get NULL, instead of the filename of the current file linked to the invoice.
With:
$builder->add('attachment', 'text')
I don't get the file input just a silly textbox BUT THIS TIME --with the name in it-- .. so how do I solve this? File Input widget and file name in it without a Document object ?!
And the second question ( I am merely at the point of throwing out all my application developed until now and move to laravel because I had a lot of "these kind of problems" ..doing simple things in symfony is almost always more complicated than in other frameworks..or maybe its my fault that I don't want to folow the guidelines and create a Document Entity?! What if I want flexibility and want to manage my database in another manner that doesn't fit in all these guidelines?)
So I am on the edit form action, I upload a new file (don't forget that I have the file set to $builder->add('attachment',file',array('data_class'=>null))
I can't get my attachment string name from the current invoice I am editing? !
public function editAction($id)
....
$invoice = $em->getRepository('AppBundle:Invoice')->find($id);
..
if ($form->isValid()) {
$oldFileName=$invoice->getAttachment(); //this is null
$oldFileName=$invoice->getId(); //this returns the invoice id
$oldFileName=$invoice->getValue(); //returns invoice value
echo 'old: '.$oldFileName.'<br/>';
exit();
}
So someone please tell me why I can't access my invoices property? Which is a string ?
I tried making a new instance I though that somehow if I create the form with the $invoice object it somehow links him to the attachment from the edit form
if ($form->isValid()) {
$sameInvoice= $em->getRepository('AppBundle:Invoice')->find(20); //hardcoded ID
$oldFileName=$sameInvoice->getAttachment(); //still null
$oldFileName=$sameInvoice->getId(); //returns 20
echo 'old: '.$oldFileName.'<br/>';
exit();
The only thing I wanted was, have a filename string in my invoice table, and test myself if the file exists in the path with that filename and if it exists, then delete it and upload the new one and so on.. why does it have to be so hard ??
Why do I have to create a entity ? Why do I have to alter my database structure (its not the case here..but what if the client doesn't want the database to be changed..so I can't insert this "Document" table).. Why can't the form builder show the data from invoice->attachment, I get it that because he needs a file data and he can't accept a string, but why aren't there guidelines for these simple tasks?!
Alright I finally managed to get it working:
So the problem why it was NULL was because it did bind the $invoice instance to the form:
$invoice = $em->getRepository('AppBundle:Invoice')->find($id);
$form = $this->createForm(new InvoiceType($id), $invoice);
After this block of code, all refferences like : $invoice->getAttachment();
Are reffered to as the form invoice object not the actual object, so basically after this I can only call things like: "getClientOriginalName()" and would show me the new file that I uploaded in the edit form.
To counter this I created a variable that stores that name initially before the $invoice object to get bind to the form
$invoice = $em->getRepository('AppBundle:Invoice')->find($id);
$oldFileName=$invoice->getAttachment(); //this is stil the object here I can see the record from the database
$form = $this->createForm(new InvoiceType($id), $invoice);
//here the $invoice->getAttachment(); returns null
So now I have the old name and I can test it like:
if ($form->isValid()) {
$fs=new Filesystem();
$newFile=$form['attachment']->getData();
$newFileName=$newFile->getClientOriginalName();
if($newFileName != $oldFileName)
{
// if($fs->exists('files/'.$this->getUser()->getId().'/'.$oldFileName))
// $fs->remove('files/'.$this->getUser()->getId().'/'.$oldFileName);
$sanitizedFilename=rand(1, 99999).'_'.$newFileName;
$dir='files/'.$this->getUser()->getId().'/';
$newFile->move($dir, $sanitizedFilename);
$invoice->setAttachment($sanitizedFilename);
}
$em->persist($invoice);
$em->flush();
return $this->redirect($this->generateUrl('my-invoices'));
}
For the other problem with the filename of the old file not appearing in the Edit Invoice Page I sent my variable to the view :
return $this->render('AppBundle:Invoices:edit.html.twig', array(
'oldFileName' => $oldFileName)
And put that value to the label of the input file widget using twig
Remain calm. You are making this much harder then it needs to be.
myControllerAction()
{
// No need for an object, an array works fine
$model = array(
'invoice' => $invoice,
'attachment' => null
);
$builder = $this->createFormBuilder($model);
$builder->setAction($this->generateUrl('cerad_game_schedule_import'));
$builder->setMethod('POST');
$builder->add('attachment', 'file');
$builder->add('invoice', new InvoiceType());
$builder->add('import', 'submit', array(
'label' => 'Import From File',
'attr' => array('class' => 'import'),
));
$form = $builder->getForm();
$form->handleRequest($request);
if ($form->isValid())
{
$model = $form->getData();
$file = $model['attachment']; // The file object is built by the form processor
if (!$file->isValid())
{
$model['results'] = sprintf("Max file size %d %d Valid: %d, Error: %d<br />\n",
$file->getMaxFilesize(), // Returns null?
$file->getClientSize(),
$file->isValid(),
$file->getError());
die($model['results'];
}
$importFilePath = $file->getPathname();
$clientFileName = $file->getClientOriginalName();
// Xfer info to the invoice object and update
}

Cake PHP file Downloading using Media view

Hi I uploaded files and stored in app/views/xxx/yyy.
Now i would like to download the files
If the file is PDF it is opened in new Tab and rest of them are downloaded, I need all files to be opened in new tab.
Here is my Code :
$this->view = 'Media';
$params = array(
'id' => $fileName,
'name' => $fileNameWOExtn,
'download' => false,
'extension' => $fileExtn, // must be lower case
'path' => APP . 'views' . DS .'static' . DS. $url .DS // don't forget terminal 'DS'
);
LogUtil::$logger->debug('Media View Params : '. var_export($params, true));
$this->set($params);
Not every file can be opened in the browser. A lot of file type encodings are proprietary and require their specific program to read and interpret them. PDFs, plain text files, some images, etc (with some exceptions) are the only types that browsers can recognize.
What types are files are you trying to render?

Wrong File Type for File Download - CakePHP

In my cakephp web page, I have a button that the user clicks and it performs some maintenance on the server and then presents a download to the user. The file download is testlogs.gzip but when the download option occurs in firefox, it comes up as a file type of html document.
The file downloads and extracts fine, but I want the file type to be correct.
Here is the Media view class for the download:
//$this->autoRender = false;
$this->viewClass = 'Media';
$params = array(
'id' => 'systemlogs',
'name' => 'testsystemlogs',
'download' => true,
'extension' => 'gzip',
// 'mimeType' => 'zip',
'path' => DS . 'home' . DS
);
$this->set($params);
I tried to add in the 'mimeType' => 'zip' but that did not work.
Any help would be great.
Thanks
UPDATE: I tested uploading of the same files and I used firebug to determine the content type. The only file types I care about are of type: application/octet-stream.
So I think I just need to set this type in the Media class settings, not sure how to do that though.
THanks
mimeType has to be specified as an associative array (extension -> type), in your case this would be array('gzip' => 'application/x-gzip'). CakePHP merges this array with the built-in array of known MIME types in CakeResponse class.
However, CakePHP already knows the MIME type of .gz files so changing the extension of your file, if it is an option, might be an even easier solution.

Multiple file upload field in custom module using drupal 7 Form API

I'm searching for a way to add a field in a custom form that will allow me to upload a list of files like this one : which is a screenshot of a File field of the file module.
I tried this : http://ygerasimov.com/d7-zip-archive-custom-file-multiple-upload
which uses ajax and custom code. My files are saved in DB but not displayed when I reload the page... I tried to make it work but with no luck.
I really hope that someone will be able to help me.
Thanks in advance,
Hervé
You can used this for custom multiple upload fields:
$form['file'] = array(
'#type' => 'file',
'#name' => 'files[]',
'#title' => t('Upload some photos'),
'#description' => t('JPG\'s, GIF\'s, and PNG\'s only, 10MB Max Size'),
'#attributes' => array('multiple' => 'multiple'),
);

Resources