Unable to upload video file with yii2 - php

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.

Related

Add watermarks to multiple images using Dropzone.js and Laravel 5.5

I have a form where a user can upload multiple images with Dropzone.js and then I store those images in the database and in the public/images folder.
But what I need is to add a watermark to all of these images before I save them in the public/images directory, because these images will show in the front-end as "preview" images.
I found documentation on how to add watermarks using Intervention Image here.
But I just cant figure out how I would proceed in adding that in my current setup.
Here is my form with the script:
<div id="file-preview_images" class="dropzone"></div>
<script>
let dropPreview = new Dropzone('#file-preview_images', {
url: '{{ route('upload.preview.store', $file) }}',
headers: {
'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content
}
});
dropPreview.on('success', function(file, response) {
file.id = response.id;
});
</script>
$file variable is when a user clicks on create a new File, it creates a new File with a unique identifier before its even saved. A file can have many uploads.
Here is my store method:
public function store(File $file, Request $request) {
// Make sure the user owns the file before we store it in database.
$this->authorize('touch', $file);
// Get the file(s)
$uploadedFile = $request->file('file');
$upload = $this->storeUpload($file, $uploadedFile);
$request->file( 'file' )->move(
base_path() . '/public/images/previews/', $upload->filename
);
return response()->json([
'id' => $upload->id
]);
}
protected function storeUpload(File $file, UploadedFile $uploadedFile) {
// Make a new Upload model
$upload = new Upload;
// Fill the fields in the uploads table
$upload->fill([
'filename' => $uploadedFile->getClientOriginalName(),
'size' => $uploadedFile->getSize(),
'preview' => 1
]);
// Associate this upload with a file.
$upload->file()->associate($file);
// Associate this upload with a user
$upload->user()->associate(auth()->user());
// Save the file
$upload->save();
return $upload;
}
All of that works as intended, I just need to add watermarks to each of these images, which I'm having trouble with.
I already saved a watermark image in public/images/shutterstock.png
I figured it out. This is what I had to do:
public function store(File $file, Request $request) {
// Make sure the user owns the file before we store it in database.
$this->authorize('touch', $file);
// Get the file(s)
$uploadedFile = $request->file('file');
$upload = $this->storeUpload($file, $uploadedFile);
// Get the image, and make it using Image Intervention
$img = Image::make($request->file('file'));
// Insert the image above with the watermarked image, and center the watermark
$img->insert('images/home/shutterstock.png', 'center');
// Save the image in the 'public/images/previews' directory
$img->save(base_path() . '/public/images/gallery/pre/'.$upload->filename);
return response()->json([
'id' => $upload->id
]);
}
And on the "storeUpload" method, changed the 'filename' too:
$upload->fill([
'filename' => $file->identifier.'-'.uniqid(10).$uploadedFile->getClientOriginalName(),
'size' => $uploadedFile->getSize(),
'preview' => 1
]);

Laravel 5 Image Upload

I am trying to upload Images with a form. I have 5 fields in total and don't want to make all fields required. However there is an exception if I leave one of the fields blank. But everything works fine when I upload all 5 images.
I have no rules in my $rules array. Something goes wrong with isValid().
Error:
FatalErrorException in ProfilesController.php line 191:
Call to a member function getClientOriginalExtension() on a non-object.
Can somebody point me into the right direction please.
My Controller:
public function update(ProfileRequest $request, $id)
{
$profile = Profile::findOrFail($id);
$request->merge([ 'wifi' => $request->has('wifi') ? true : false,
'takeaway'=> $request->has('takeaway') ? true : false,
'ec'=> $request->has('ec') ? true : false,
'creditcard'=> $request->has('creditcard') ? true : false,
'cash'=> $request->has('cash') ? true : false,
'wheelchair'=> $request->has('wheelchair') ? true : false,
'outdoor'=> $request->has('outdoor') ? true : false,
'tv'=> $request->has('tv') ? true : false,
'service'=> $request->has('service') ? true : false,
'smoking'=> $request->has('smoking') ? true : false,
'reservation'=> $request->has('reservation') ? true : false,
'brunch'=> $request->has('brunch') ? true : false,
]);
// getting all of the post data
$file = array('image_profilehero' => Input::file('image_profilehero'),
'image_avatar' => Input::file('image_avatar'),
'pdf' => Input::file('pdf'),
'restaurantscene1' => Input::file('restaurantscene1'),
'restaurantscene2' => Input::file('restaurantscene2')
);
// setting up rules
$rules = array(//'image_profilehero' => 'required',
//'image_avatar' => 'required'
); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
return Redirect::to('backend/profile')->withInput()->withErrors($validator);
}
else {
// checking file is valid.
if (Input::file('image_profilehero') or Input::file('image_avatar')->isValid() or Input::file('pdf')->isValid() or Input::file('restaurantscene1')->isValid() or Input::file('restaurantscene2')->isValid()) {
$destinationPathAvatar = 'uploads/avatar'; // upload path Avatar
$destinationPathProfileHero = 'uploads/profilehero'; // upload path ProfileHero
$destinationPathPdf = 'uploads/speisekarten'; // upload path ProfileHero
//Restaurant Scene Bilder
$destinationPathRestaurantScene1 = 'uploads/restaurantscene'; // upload path RestaurantScene
$destinationPathRestaurantScene2 = 'uploads/restaurantscene'; // upload path RestaurantScene
$extensionAvatar = Input::file('image_avatar')->getClientOriginalExtension(); // getting image extension
$extensionProfileHero = Input::file('image_profilehero')->getClientOriginalExtension(); // getting image extension
$extensionPdf = Input::file('pdf')->getClientOriginalExtension(); // getting image extension
$extensionRestaurantScene1 = Input::file('restaurantscene1')->getClientOriginalExtension(); // getting image extension
$extensionRestaurantScene2 = Input::file('restaurantscene2')->getClientOriginalExtension(); // getting image extension
//$fileName = rand(11111,99999).'.'.$extension; // renameing image
$fileNameAvatar = '/avatar/avatar_'.Auth::user()->id.'.'.$extensionAvatar;
$fileNameProfieHero = '/profilehero/profilehero_'.Auth::user()->id.'.'.$extensionProfileHero;
$fileNamePdf = '/speisekarten/pdf_'.Auth::user()->id.'.'.$extensionPdf;
$fileNameRestaurantScene1 = '/restaurantscene/scene1_'.Auth::user()->id.'.'.$extensionRestaurantScene1;
$fileNameRestaurantScene2 = '/restaurantscene/scene2_'.Auth::user()->id.'.'.$extensionRestaurantScene2;
Input::file('image_profilehero')->move($destinationPathProfileHero, $fileNameProfieHero); // uploading file to given path
Input::file('image_avatar')->move($destinationPathAvatar, $fileNameAvatar); // uploading file to given path
Input::file('pdf')->move($destinationPathPdf, $fileNamePdf); // uploading file to given path
Input::file('restaurantscene1')->move($destinationPathRestaurantScene1, $fileNameRestaurantScene1); // uploading file to given path
Input::file('restaurantscene2')->move($destinationPathRestaurantScene2, $fileNameRestaurantScene2); // uploading file to given path
// sending back with message
return redirect('backend/profile')->with([
'flash_message_important' => false,
'flash_message' => 'All done'
]);
}
else {
// sending back with error message.
return redirect('backend/profile')->with([
'flash_message_important' => false,
'flash_message' => 'Upps. Something's wrong.'
]);
}
}
//return redirect('backend/profile');
$profile->update($request->all());
}
Your code is not accounting for an empty or missing file, it's just assuming there's a file there and attempting to move it. So you end up calling methods on a non-object, likely null. You just need to do a bit of extra work to ensure you actually have objects before you call methods on them, like this:
$pdf = Input::file('pdf');
if ($pdf) {
$extension = $pdf->getClientOriginalExtension();
$pdf->move($destinationPathPdf, $fileNamePdf);
}
This way, if there's no PDF file, the if statement will be false and will skip calling methods on it, so you avoid that kind of error. It's generally good practice to do this.

Download a PDF file instead of displaying it with CodeIgniter

I am generating PDF file using CodeIgniter and R&OS pdf class.
But now the problem is that the pdf is displayed to the browser.
I instead want it to be downloaded.
Here is my code :
$this->load->library('cezpdf');
$data['users'] = $this->user->get_all_ayant_droits();
foreach($data['users'] as $user) {
$db_data[] = array('name' => $user->nom, 'department' => $user->Department, 'status' => $user->Status);
}
$col_names = array(
'name' => 'Noms et Prenoms',
'department' => 'Département',
'status' => 'Status'
);
$this->cezpdf->ezTable($db_data, $col_names, 'Ayant droit Base Loisirs de Kribi', array('width'=>550));
$this->cezpdf->ezStream();
What is missing for this controller to send the file to download ?
You can pass the argument to the function ezStream
$this->cezpdf->ezStream(array $options);
$options 'compress' => 0/1 to enable compression. For compression level please use $this->options['compression'] = at the very first point. Default: 1
'download' => 0/1 to display inline (in browser) or as download. Default: 0
You can use Download Helper https://ellislab.com/codeigniter/user-guide/helpers/download_helper.html?
$this->load->helper('download');
$data = $this->cezpdf->ezStream();
force_download("PDF_filename.pdf", $data);
You can also use ouput variable by setting proper header value.
$this->output->set_header('Content-Disposition: attachment; filename="PDF_filename.pdf"');
$this->output->set_content_type('application/pdf')
->set_output($this->cezpdf->ezStream());
here by setting content type to appication/pdf so browser identify content is pdf and Content-Disposition: attachment force to download the file.
Hope this helps. Sorry for poor English.

drupal 6: file upload in form not working

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.

Uploaded docx files turning into zip

I am currently using symfony 1.4 and would like to allow users to upload Microsoft Word docx files. Using the sfWidgetFormInputFile widget and sfValidatorFile below users are able to select and successfully upload their docx files using a simple web form.
$this->widgetSchema['file_name'] = new sfWidgetFormInputFile(array('label' => 'File'));
$this->validatorSchema['file_name'] = new sfValidatorFile(array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_dir_file_sharing').DIRECTORY_SEPARATOR,
'mime_types' => array('application/msword',
'application/vnd.ms-word',
'application/msword',
'application/msword; charset=binary')
), array(
'invalid' => 'Invalid file.',
'required' => 'Select a file to upload.',
'mime_types' => 'The file must be a supported type.'
));
The problem is that after the file is uploaded, the extension is changed to .zip and the file contains a file tree of xml files. My understanding is that this is because Office 2007 are now using Open xml file formats. Is there any way to prevent this from happening using symfony or PHP?
The problem is Content-Sniffing. The new Office formats ARE .zip files, and if on upload, the content is sniffed, the browser will identify this as a ZIP file and set the Content-Type header as such. Similarly, on download unless your server sets the proper Content-Type HTTP response header, the browser will assume that this is a ZIP file.
Symfony 1.3+ has an option mime_type_guessers for sfValidatorFile which allows you to define your own mime type guesser PHP callable or use a build in guesser. Calling any of the 3 built-in mime type guessers finds the correct file type for docx and keeps the the docx file extension.
Here is the updated code using guessFromFileinfo:
$this->validatorSchema['file_name'] = new sfValidatorFile(array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_dir_file_sharing').DIRECTORY_SEPARATOR,
'mime_type_guessers' => array('guessFromFileinfo'),
'mime_types' => array('application/msword',
'application/vnd.ms-word',
'application/msword',
'application/msword; charset=binary')
), array(
'invalid' => 'Invalid file.',
'required' => 'Select a file to upload.',
'mime_types' => 'The file must be a supported type.'
));
It seems to be a bug in Symfony's file type detection. A workaround is described.
The suggested use of mime_type_guessers uses a non-existing function.
If you want to use the sfValidatorFile method, you should write array(array('sfValidatorFile', 'guessFromFileinfo')).
The suggested solution uses no mime-type detection at all and results in problems with the classic excel format on my system.
I fixed the problem by extending the sfValidatorFile class and changing the getMimeType method.
Create a new msValidatorFile.class.php file in your lib folder :
<?php
class msValidatorFile extends sfValidatorFile
{
protected function getMimeType($file, $fallback)
{
$arrayZips = array( "application/zip",
"application/x-zip",
"application/x-zip-compressed");
$officeTypes = array(
"application/vnd.ms-word.document.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.wordprocessingml.template",
"application/vnd.ms-powerpoint.template.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.template",
"application/vnd.ms-powerpoint.addin.macroEnabled.12",
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.slideshow",
"application/vnd.ms-powerpoint.presentation.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.ms-excel.addin.macroEnabled.12",
"application/vnd.ms-excel.sheet.binary.macroEnabled.12",
"application/vnd.ms-excel.sheet.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-excel.template.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.spreadsheetml.template");
foreach ($this->getOption('mime_type_guessers') as $method)
{
$type = call_user_func($method, $file);
if (null !== $type && $type !== false)
{
if (in_array($type, $arrayZips) && in_array($fallback, $officeTypes))
{
return $fallback;
}
return strtolower($type);
}
}
return strtolower($fallback);
}
}
Use this new validator in your form code :
$this->validatorSchema['file'] =
new msValidatorFile(array('required' => false,
'path' => sfConfig::get('sf_upload_dir')
));

Categories