Symfony2 / File Upload - guessExtension on null if file field is empty - php

I have file field with required = false, multiple=multiple. Everything works fine, but if file input is empty, symfony2 show me this error.
Error: Call to a member function guessExtension() on null
Here is my form type:
->add('file', 'file', array(
'multiple' => 'multiple',
'data_class' => null,
'required' => false,
'mapped' => false,
'attr' => array(
'maxSize' => '1024k',
'accept' => 'image/*',
)
))
Upload function:
private function uploadImg($files)
{
$path = array();
foreach ($files as $file) {
$extension = $file->guessExtension();
if (!$extension) {
$extension = 'bin';
}
$randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
$file->move('uploads/images/', $randomName);
$path[] = $randomName;
}
return $path;
}
How can I check if file input is empty?
$form['file']->getData(); every time returns Array

You can use continue to skip empty files
foreach ($files as $file) {
if(!$file) {
continue; //skip
}
$extension = $file->guessExtension();
if (!$extension) {
$extension = 'bin';
}
$randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
$file->move('uploads/images/', $randomName);
$path[] = $randomName;
}

For Symfony 3, I used this method and working fine.
use Symfony\Component\HttpFoundation\File\UploadedFile;
public function updateAction(...){
// $image is Entity property, change accordingly.
$file = $item->getImage();
if ($file instanceof UploadedFile) {
... upload code
}
}

Related

insert images coming from more than input file [duplicate]

Now I use a simple way to upload images:
if ($request->hasFile("images")) {
$file = $request->file("images");
// Do uploading to Storage
$uploaded = Storage::put($destinationPath. $fileName, file_get_contents($file->getRealPath()));
}
How can I upload multiple files when I have: images[] in HTML form?
Is it possible to do with Storage::put()?
If your form is submitting multiple files under images[] array, you would loop through them accordingly.
It would help if you posted the form html as well.
<?php
$files = $request->file("images");
$uploaded = [];
if($files){
foreach($files as $file) {
$uploaded[] = Storage::put($destinationPath. $fileName, file_get_contents($file->getRealPath()));
}
}
});
In the view (using the LaravelCollective package):
{{ Form::open(['action' => 'MyController#store', 'class' => 'form-horizontal', 'files' => true, 'enctype' => 'multipart/form-data' ]) }}
{{ Form::file('attachments[]', ['class' => 'form-control', 'roles' => 'form', 'multiple' => 'multiple']) }}
{{ Form::close() }}
In the controller:
public function store(Request $request)
{
if (($request->has('attachments'))) {
$files = $request->file('attachments');
$destinationPath = storage_path() . '/app/public/';
foreach ($files as $file) {
$fileName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$storeName = $fileName . '.' . $extension;
// Store the file in the disk
$file->move($destinationPath, $storeName);
}
}
}

Upload file in Laravel - wrong path

I am beginner in Laravel.
I have this code:
if ($request->hasfile('profilePhoto')) {
$this->validate($request, [
'profilePhoto' => 'required',
'profilePhoto.*' => 'mimetypes:image/jpg'
]);
$image = $request->file('profilePhoto');
$extension = strtolower($image->getClientOriginalExtension());
$path = 'upload/images/UserImage/';
$uniqueName = md5($image . time());
$image->move(public_path($path), $uniqueName . '.' . $extension);
}
This function uploads files to public/upload/images/UserImage/.
I need it to store it in storage/app/upload/images/UserImage/ instead
How can I rewrite my code?
You have to use storage_path function ("storage/app/upload" folder must exist):
$image->move(storage_path("app/upload"), $uniqueName . '.' . $extension);
if ($request->hasfile('profilePhoto')) {
$this->validate($request, [
'profilePhoto' => 'required',
'profilePhoto.*' => 'mimetypes:image/jpg'
]);
$image = $request->file('profilePhoto');
$extension = strtolower($image->getClientOriginalExtension());
$path = storage_path('app/public/upload/images/UserImage');
$uniqueName = md5($image . time());
$image->move(public_path($path), $uniqueName . '.' . $extension);
}
A common way in Laravel to upload to storage/app is through the local disk driver.
$file = $path . $uniqueName . '.' . $extension;
\Storage::disk('local')->put($file, $request->file('profilePhoto'));
Storage::disk('local') points to storage/app/.
As your $path variable is already declared like this $path = 'upload/images/UserImage/' .So instead of storing data to public_path you can store to storage_path().
$image->move(storage_path($path), $uniqueName . '.' . $extension);

How to Store Image in Database Using Laravel With Base URL

When I'm storing an image into a database, then it doesn't upload with base URL. How can resolve this type of problem in Laravel?
public function uploadimage(Request $request)
{
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His') . '-' . $filename;
$file->move(public_path('img'), $picture);
$employee_image = Image::create($request->all());
$employee_image->image = $filename;
$employee_image->save();
return response()->json(['message' => 'Image Uploaded Successfully']);
}
return response()->json(['message' => 'Select image first.']);
}
The public_path() function does not intend to be use to serve browser friendly uri, so, you should use \Illuminate\Support\Facades\URL facade instead.
e.g.:
$employee_image->image = URL::asset('storage/employees/').$filename;
$employee_image->save();
Source: Laravel.IO
Try this ....
public function uploadimage(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$employees = new Image($request->input()) ;
if($file = $request->hasFile('image')) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$employees->image = '/public/images/'.$fileName ;
}
$employees->save() ;
return response()->json(['message' => 'Image Uploaded Successfully']);
}

Recursive function in cakePHP

In a controller action, I handle the file upload like following (in short):
$originalFileName = $meetingsTask['submitted_file']['name'];
$file = $meetingsTask['submitted_file'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
$arr_ext = array('jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xlsx', 'xls', 'xlt', 'xlm', 'ods','ppt', 'pot', 'pps' );
if(!in_array($ext, $arr_ext)){
...code omitted...
}
$newFileName = $this->generateFileName( $originalFileName );
...logic continues...
The problem is that generateFileName function always returns empty when file name already exists. Here is the function itself:
public function generateFileName( $fileName ){
if( $this->Tasks->checkFileName( $fileName ) ){
$prefix = rand(1, 1000);
$fileName = $prefix . '_' . $fileName;
$this->generateFileName( $fileName );
}else{
return $fileName;
}
}
checkFileName() only returns true/false depending on the existance of filename in the database.
What could be causing the trouble?
Any help or guidance is much appreciated.
If I understand correctly what you want, the recursion in not needed
public function generateFileName( $fileName ) {
// Start with source filename
$new = $fileName;
while( $this->Tasks->checkFileName( $new ) ) {
// If file exist try new prefix
$prefix = rand(1, 1000);
$new = $prefix . '_' . $fileName;
}
return $new;
}

Resize image file laravel 5

I installed the patch "intervention/image", "must-master" in order to make my image to reduce the size of it to 300 by 300.
I've done some forms and appears to me always the same mistake.
Call to a member function resize() on string
which got the error?
Controller
public function updateProfile() {
$file = Input::file('imagem');
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
if ($file == null) {
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return view('backend/perfil.index');
}
$file = array_get($profileData,'imagem');
$destinationPath = 'imagens/perfil';
$extension = $file->getClientOriginalExtension();
$filename = rand(11111, 99999) . '.' . $extension;
$reduzir = $filename -> resize (300,300);
$profileData['imagem'] = $filename;
$upload_success = $file->move($destinationPath, $filename);
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil');
} else {
return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
}
}
The issue might be because of these reasons
Have you added this aliases in your app.php
'aliases' => [
//add these three at the bottom
'Form' => Illuminate\Html\FormFacade::class,
'HTML' => Illuminate\Html\HtmlFacade::class,
'Image' => Intervention\Image\Facades\Image::class
],
I believe that you already have form and html helper.
And use this function in the Controller
i.e., just pass the image and size value as the Parameter to this function
In the controller you have just call the below function like
$resizedImage = $this->resize($image, $request->get('image_size'));
And the resize() function was given below
private function resize($image, $size)
{
try
{
$extension = $image->getClientOriginalExtension();
$imageRealPath = $image->getRealPath();
$thumbName = 'thumb_'. $image->getClientOriginalName();
//$imageManager = new ImageManager(); // use this if you don't want facade style code
//$img = $imageManager->make($imageRealPath);
$img = Image::make($imageRealPath); // use this if you want facade style code
$img->resize(intval($size), null, function($constraint) {
$constraint->aspectRatio();
});
return $img->save(public_path('images'). '/'. $thumbName);
}
catch(Exception $e)
{
return false;
}

Categories