Errors uploading more than one file in laravel 5 - php

I am building a form that allows users upload more than one file provided they click on the 'Add more files' link. When I upload more than one file, for example, 2 files, I see the 2 files in the folder I store files but in database table, its only the first of the 2 files that is saved on the table. And it is saved twice. For instance, if I upload 3 files, the first of the 3 files is saved 3 times on the table but the 3 individual files I can see in the folder. Whats the problem here?
My view:
<label class="control-label mb-10" for="exampleInputuname_1">Uploads</label>
<input type="file" class="form-control" id="exampleInputuname_1"
name="file[]" required>
<a class="add_more" href="">Add More Files</a>
JQuery
$( function() {
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' class='form-control'/>");
});
});
My controller
foreach ($files as $file) {
$file_extension = $file->getClientOriginalExtension();
$new_name = base64_encode(date('Y-m-d H:i:s') . $file->getClientOriginalName()) . '.' . $file_extension;
$destinationPath = 'uploads/files';
$file->move($destinationPath, $new_name);
$filename = $destinationPath . '/' . $new_name;
$i++;
$uri = Utilities::generateFileRef($i);
File::create([
'uri' => $uri,
'user_id' => $user_id,
'title' => $request->folder_name,
'document' => $filename,
'folder_id' => $folder_id
]);
}

Related

How to set a name to uploaded file instead of random numbers by using carbon in laravel

When I upload an image it set as random numbers like //15215653352.png. But instead I have my images must be precise , and that means I have a folder which has the pictures set organized(digital_1.png,digital_2.png,digital_3.png...)
##The folder of images is in public called imagg##
Inside the productFactory I'm using this :
'image' => 'digital_'.$this->faker->unique()->numberBetween(1,28).'.png',
To add a picture I have this code :
$imageName = Carbon::now()->timestamp.'.'. $this->image->extension();
$this->image->storeAs('imagg',$imageName,'public');
$product->image = $imageName;
The items-component.blade.php:
#foreach ($products as $product)
<!-- grid item #1 -->
<a href="{{route('product.details',$product->slug)}}">
<div id="TEST" class="activities-grid-item bla" style=" background-image: url({{asset('imagg')}}/{{$product->image}}" >
<h1 class="activities-h1">
.
.
.
</a>
$endforeach
the filesystem.php:
'root' => storage_path('app'),
So therefore the images cannot be displayed with those random numbers but they must be named suc has digital_x.png (while x is variable from 1 to 28 , and existed in the imagg folder).
This should work.
try {
$dir = 'folder/to_the_images/'; // path to the images
if (is_dir($dir)) {
$images = glob($dir . '{*.jpg, *.JPG, *.jpeg}');
$imageName = 'digital_' . count($images) + 1 . '.' . $this->image->extension();
$this->image->storeAs('imagg', $imageName, 'public');
$product->image = $imageName;
}
} catch (\Exception $exception) {
die('saving images failed ' . $exception->getMessage());
}

how can i keep saved files in a cell everytime i upload a new file? am using laravel 5.5

I created a user table with employee's details, and in my image column I have a file uploaded in its cell. How can I keep old file every time I upload a new file.
my view.blade
<input type="file" name="image[]" class="form-control" value="{{ $employee['image'] }}" multiple>
<th> {{$employee['image']}}</th>
my controller
if($request->hasfile('image')){
$files = [];
foreach ($request->image as $image) {
$path = $image->getClientOriginalName();
$filename = time() . '-' . $path;
$files[] = $filename;
$image->storeAs('employees', $employee->id . '/' . $filename);
$image->move(public_path('employees'),$filename);
}
$files = implode("</br>;", $files);
}
$employee->image = $files;
$employee->save();
Just change one line :
$employee->image = $files;
to,
$employee->image = $employee->image . $files;

file upload laravel 5

Hi I'm trying to upload an image with Laravel 5
Function is:
$file_name = '';
//validation of image before uploading and saving
if( Input::hasFile('img') && Input::file('img')->isValid() ){
$file = Input::file('img'); //creating an object
$file_name = str_random(30) . '.' . $file->getClientOriginalExtension(); //randon str name to img file with the ext of the original file
$file->move( public_path() . '\assets\img', $file_name);
}
form: multipart/form-data
input: input type="file" name="img"
The problem is that there's always an empty value in $file_name
Your form opening tag should have enctype="multipart/form-data". Look like this:
<form method="POST" enctype="multipart/form-data">
And to move your image in storage, write your code in controller like this:
public function store(Request $request)
{
if($request->hasFile('img') && $request->file('img')->isValid()){
$file = $request->file('img');
$file_name = str_random(30) . '.' . $file->getClientOriginalExtension();
$file->move(base_path() . '/assets/img', $file_name);
}
}

PHP - Resize image on upload AND keep original

I'm creating a site using Laravel 4, which allows an admin to upload a large number of images at a time. Currently, I'm able to do just that, where each image is given its own unique ID and put into its own folder named with the same ID.
The problem is that I need the application to also upload a second, resized (smaller) version of the image along with the original. I learned that you must resize an image on the client side, so I'm not sure how I would go about saving the original image, as well as smaller version. The smaller image should be named using the same ID, with some sort of identifier like "-smaller" at the end of the name.
Here's my current front end;
{{ Form::open(array('url' => 'imageUpload', 'files' => true, 'method' => 'post'))}}
<div class="form-group">
<label for="fileToUpload" class="col-sm-2 control-label">Choose All Images</label>
</br>
{{ Form::file('images[]', ['multiple' => true]) }}
</div>
<div class="col-sm-offset-2 col-sm-10">
{{ Form::submit('Add Photos', ['class' => 'btn btn-large btn-primary openbutton'])}}
<!--<button type="submit" class="btn btn-default">Sign in</button> -->
</div>
{{ Form::close() }}
And here's my controller;
$files = Input::file('images');
foreach($files as $file) {
$rules = array(
'file' => 'required|mimes:png,gif,jpeg,txt,pdf,doc,rtf|max:9999999999'
);
$validator = \Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$id = Str::random(14);
$id = $race . "-" . $id;
$destinationPath = 'raceImages/' . $id;
//$filename = $id;
$filename = $file->getClientOriginalName();
$mime_type = $file->getMimeType();
$extension = $file->getClientOriginalExtension();
$upload_success = $file->move($destinationPath, $id);
);
} else {
return Redirect::back()->with('error', 'I only accept images.');
}
}
This is how I resolved the same problem in my app:
Install this package: https://github.com/Intervention/image
Use this code:
$createnew = new Yourmodelname;
$avatar = Input::file('pic_path');
if (isset($avatar)) { //will process the code only if an image was properly pointed in the form
$image = Input::file('pic_path');
var_dump($image->getRealPath()); // just for error tracking
$filename = $image->getClientOriginalName();
if (Image::make($image->getRealPath())->save('foldername/yourprefix_' . $LastInsertId . '_' . $filename)) { } // foldername is related to your public folder
if (Image::make($image->getRealPath())->widen(200)->save('foldername/thumbs/thumb_yourprefix_' . $LastInsertId . '_' . $filename)) {
}
$createnew->pic_path = 'event_poster_' . $LastInsertId . '_' . $filename;
$createnew->pic_thumb = 'event_poster_thumb_' . $LastInsertId . '_' . $filename;
$createnew->save();
}
Now you have two files: one original (no changes) and a thumbnail scaled proportionally to width 280.
Other resize options you can find in the Intervention docs.

Zend addFilter rename single file only

I have an upload form that has two file input's.
I want to rename the files so that each have a unique name. Here is what I have in my Controller
public function mainAction()
{
$upload = new Zend_File_Transfer();
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
$upload->addFilter('Rename', uniqid($file.'_').'.csv', $file);
}
$upload->receive();
}
Even though I have specified the file as the last paramter in setFilter, it renames both files at the same time so that they end up with the same name.
I figured out how to do it.
This is the form:
<input type="file" name="one">
<input type="file" name="two">
this goes in the controller
$renamefile1 = new Zend_Filter_File_Rename(array(
'target' => $path.'/file1.csv', // path to file
'overwrite' => true
));
//rename file 2 to file2
$renamefile2 = new Zend_Filter_File_Rename(array(
'target' => $path.'/file2.csv', // path to file
'overwrite' => true
));
$names = $upload->getfileName();
$file1 = $renamefile1->filter($names["one"]);
$file2 = $renamefile2->filter($names["two"]);

Categories