file upload laravel 5 - php

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);
}
}

Related

Failed to rename image and upload using storeAs in Laravel

I created a form to store article with an image , and generate a resized version as thumbnail from it.
I want the image to be renamed after the article slug and stored in the "public/img/articles-images " directory but i keep receiving : "Image source not readable" error
This is the image upload handler function in my controller :
private function handleRequest($request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug;
$successUploaded = $image->storeAs('img/articles-images', $fileName);
if($successUploaded) {
$width = config('cms.image.thumbnail.width');
$height = config('cms.image.thumbnail.height');
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make('img/articles-images' . '/' . $fileName)
->resize($width, $height)
->save('img/articles-images' . '/' . $thumbnail);
}
$data['image'] = $fileName;
}
return $data;
}
storeAs() method, which receives the path, the file name, and the (optional) disk as its arguments :
$successUploaded = $request->file('image')->storeAs(
'images', $fileName
);
I solved it ! Apparently there was no need to storeAs() method at all , the new code is like below :
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug.'.' .$image->getClientOriginalExtension();
$destination = $this->uploadPath;
$successUploaded = $image->move($destination, $fileName);
// //

Image uploaded in Laravel 5.8 keep saving as private image

I am trying upload a single image into a Post and it keeps saving it as a private image--heck, I don't even know where to find that file.
PostController.php
...
if ($request->hasFile('photo')) {
$photo = $request->photo;
$ext = $photo->getClientOriginalExtension();
$filename = uniqid() . '.' . $ext;
$photo->storeAs('public/posts/' . $request->user()->id, $filename);
}
...
storeAs() function takes three parameters.
storeAs(path,name,options)
'options' is where you specify file visibility. In your case :
if ($request->hasFile('photo')) {
$photo = $request->photo;
$ext = $photo->getClientOriginalExtension();
$filename = uniqid() . '.' . $ext;
$photo->storeAs('posts/' . $request->user()->id, $filename,'public');
}

Laravel 5.5 - multiple images upload

I have this function in my controller:
use File;
use Image; //image intervention library
...
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
$path = $folderpath . $filename;
Image::make($file)->resize(800,400)->save($path);
endforeach;
endif;
return 'success';
}
which only save the last image if I upload multiple.
and I tried:
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
$path = $folderpath . $filename;
$file->save($path);
endforeach;
endif;
return ''success;
}
which throw me error:
Method save does not exist.
I goggled and it seems like I did not instantiate it with model. But in this case, how can I instantiate it with model if it is just a direct file upload?
What is the best way for multiple images upload in laravel?
Update
After reading #kunal's answer, I managed to solve the issue by adding a unique number for the file name:
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
$count = 0;//<-- add a counter
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '_' . $count . '.' . $file->getClientOriginalExtension();//<-- add counter to the file name
$path = $folderpath . $filename;
Image::make($file)->resize(800,400)->save($path);
$count ++;//<-- increase the value
endforeach;
endif;
return 'success';
}
May be you are looking for this kind of stuff:-
if ($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file){
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$folderpath = 'images'.'/';
$file->move($folderpath , $fileName);
}
}
<input type="file" id="gallery" name="files[]" multiple />
I am thinking u may missed this part
<input type="file" id="gallery" name="file[]" />
note the file[] it must be array otherwise it will only save the last image if upload multiple image
If u did ur html part correct, then use like this,
foreach ($file as $photo) {
$path = Storage::putFile('foldername', $photo);
}
try this code:
$files= Input::file('image');
$destinationPath= 'images';
$images=array();
foreach($files as $file){
$fullname= $file->getClientOriginalName();
$hashname = $fullname;
$upload_success =$file->move($destinationPath, $hashname);
$images[]=$fullname;
$has= implode(",",$images);
}
$modelname= new Modelname;
$modelname->image_attachment = $has;
$modelname->save();
and yout html page:
<input type="file" id="image" name="image[]" />
It is not that complicated.
As of larval 5.8 you can do this:
collect($request->images)->each(function ($image) {
return $image->store('images', 'public');
});
It puts images in images folder of public disk.

Laravel 5.3 photo upload with plupload directory related issue

I have recently migrated my code into laravel. I have faced problem with file upload using plupload with laravel. In pluploaded file is uploaded to server before form submitting. After uploaded file succesfully, file path is put in hidden input field.
My Upload Code is given below.
public function photo(){
$target_file = "";
$this->target_dir = base_path() ."/uploads/";
if($_FILES['file']['name']){
$filename = AppUtils::get_new_filename($this->ext);
$filename = "photo_" . $filename;
$target_file = $this->target_dir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$photo = $this->target_dir . $filename;
echo $photo;
die();
}
else{
AppUtils::fail();
}
}
Problem is without using base_path() in $target_dir, file is not uploaded properly. But using base_path() preview image not actual location.
For example, After uploading photo output will be /var/www/htm/lar/uploads/xyz.jpg
But in preview image path shows : http://example.com/lar/var/www/html/lar/uploads/xyz.jpg
Try this:
public function photo(){
$target_file = "";
$this->target_dir = "/uploads/";
if($_FILES['file']['name']){
$filename = AppUtils::get_new_filename($this->ext);
$filename = "photo_" . $filename;
$target_file = base_path() . $this->target_dir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$photo = $this->target_dir . $filename;
echo $photo;
die();
}
else{
AppUtils::fail();
}
}
base_path() should only be used for the upload location.

Uploading image to with custom name in Yii framework

I am trying to upload images from registration form in Yii framework. The image will be saved in "img/avatar" folder and the name of the image should be changed to the username. The piece of code I use for this is below:
//uploading avatar to the img/avatar folder
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$personModel->picture = $upload_file;
$picture_name = $userModel->username;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name);
}
$personModel->save();
//end of image uploading part
The problem is: the name of the username has been saved in picture row of the database. But the image was not uploaded to the folder. I am trying to find out the problem in the code. but cannot solve it. Any suggestions?
Well first thing you need to do is to prevent database input if the picture is not saved.
if(isset($uploadedfile))
{
if($upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name)
{
$personModel->save();
}
else
{
//throw error
}
}
As far as problems in the code go. Most common problem is directories not existing, path to them not being correct.
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$ext = pathinfo($upload_file->picture, PATHINFO_EXTENSION);
$picture_name = $userModel->username . '.' . $ext;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs('/Your_correct_path/.../etc/'.$picture_name);
}
$personModel->save();
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$picture_name = $userModel->username . '.' . pathinfo($upload_file, PATHINFO_EXTENSION);
$personModel->picture = $picture_name;
if (isset($upload_file)) {
$upload_file->saveAs(Yii::app()->basePath . '/../img/avatar/' . $picture_name);
}
$personModel->save();
You have to check your folder permission.
The problem has been solved through following code:
$uploadFile = CUploadedFile::getInstance($personModel, 'picture');
$extension = pathinfo($uploadFile, PATHINFO_EXTENSION);
$fileName = $userModel->username . '.' . $extension;
if (isset($uploadFile)) {
$personModel->picture = $fileName;
$uploadFile->saveAs(Yii::app()->basePath . '/../img/avatar/' . $fileName);
}

Categories