laravel 5.4 upload image - php

My controller code for upload file in laravel 5.4:
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
Image was successfully uploaded but the code threw an exception :
FileNotFoundException in MimeTypeGuesser.php line 123
The file is there any fault in my code or is it a bug in laravel 5.4, can anyone help me solve the problem ?
My view code:
<form enctype="multipart/form-data" method="post" action="{{url('admin/post/insert')}}">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput">File input</label>
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="">submit</label>
<input class="form-control" type="submit">
</div>
</form>

Try this code. This will solve your problem.
public function fileUpload(Request $request) {
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('input_img')) {
$image = $request->file('input_img');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}

You can use it by easy way, through store method in your controller
like the below
First, we must create a form with file input to let us upload our file.
{{Form::open(['route' => 'user.store', 'files' => true])}}
{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}
{{Form::close()}}
Here is how we can handle file in our controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
// get current time and append the upload file extension to it,
// then put that name to $photoName variable.
$photoName = time().'.'.$request->user_photo->getClientOriginalExtension();
/*
talk the select file and move it public directory and make avatars
folder if doesn't exsit then give it that unique name.
*/
$request->user_photo->move(public_path('avatars'), $photoName);
}
}
That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.

A good logic for your application could be something like:
public function uploadGalery(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/storage/galeryImages/');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}

Use the following code:
$imageName = time().'.'.$request->input_img->getClientOriginalExtension();
$request->input_img->move(public_path('fotoupload'), $imageName);

public function store()
{
$this->validate(request(), [
'title' => 'required',
'slug' => 'required',
'file' => 'required|image|mimes:jpg,jpeg,png,gif'
]);
$fileName = null;
if (request()->hasFile('file')) {
$file = request()->file('file');
$fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
$file->move('./uploads/categories/', $fileName);
}
Category::create([
'title' => request()->get('title'),
'slug' => str_slug(request()->get('slug')),
'description' => request()->get('description'),
'category_img' => $fileName,
'category_status' => 'DEACTIVE'
]);
return redirect()->to('/admin/category');
}

Intervention Image is an open source PHP image handling and manipulation library
http://image.intervention.io/
This library provides a lot of useful features:
Basic Examples
// open an image file
$img = Image::make('public/foo.jpg');
// now you are able to resize the instance
$img->resize(320, 240);
// and insert a watermark for example
$img->insert('public/watermark.png');
// finally we save the image as a new file
$img->save('public/bar.jpg');
Method chaining:
$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');
Tips: (In your case)
https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false
Tips 1:
// Tell the validator input file should be an image & check this validation
$rules = array(
'image' => 'mimes:jpeg,jpg,png,gif,svg // allowed type
|required // is required field
|max:2048' // max 2MB
|min:1024 // min 1MB
);
// validator Rules
$validator = Validator::make($request->only('image'), $rules);
// Check validation (fail or pass)
if ($validator->fails())
{
//Error do your staff
} else
{
//Success do your staff
};
Tips 2:
$this->validate($request, [
'input_img' =>
'required
|image
|mimes:jpeg,png,jpg,gif,svg
|max:1024',
]);
Function:
function imageUpload(Request $request) {
if ($request->hasFile('input_img')) { //check the file present or not
$image = $request->file('input_img'); //get the file
$name = "//what every you want concatenate".'.'.$image->getClientOriginalExtension(); //get the file extention
$destinationPath = public_path('/images'); //public path folder dir
$image->move($destinationPath, $name); //mve to destination you mentioned
$image->save(); //
}
}

if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = time() . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
or follow
https://laracasts.com/discuss/channels/laravel/image-upload-file-does-not-working
or
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12

i think better to do this
if ( $request->hasFile('file')){
if ($request->file('file')->isValid()){
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('images' , $name);
$inputs = $request->all();
$inputs['path'] = $name;
}
}
Post::create($inputs);
actually images is folder that laravel make it automatic and file is name of the input and here we store name of the image in our path column in the table and store image in public/images directory

// get image from upload-image page
public function postUplodeImage(Request $request)
{
$this->validate($request, [
// check validtion for image or file
'uplode_image_file' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
// rename image name or file name
$getimageName = time().'.'.$request->uplode_image_file->getClientOriginalExtension();
$request->uplode_image_file->move(public_path('images'), $getimageName);
return back()
->with('success','images Has been You uploaded successfully.')
->with('image',$getimageName);
}

This code will store the image in database.
$('#image').change(function(){
// FileReader function for read the file.
let reader = new FileReader();
var base64;
reader.readAsDataURL(this.files[0]);
//Read File
let filereader = new FileReader();
var selectedFile = this.files[0];
// Onload of file read the file content
filereader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
$("#pimage").val(JSON.stringify(base64));
};
filereader.readAsDataURL(selectedFile);
});
HTML content should be like this.
<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
<input id="image" type="file" class="inputMaterial" name="image">
<input type="hidden" id="pimage" name="pimage" value="">
<span class="bar"></span>
</div>
Store image data in database like this:
//property_image longtext(database field type)
$data= array(
'property_image' => trim($request->get('pimage'),'"')
);
Display image:
<img src="{{$result->property_image}}" >

public function ImageUplode(Request $request) {
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = $request['code'].'.jpg';
//move image to public/image folder
$file->move(public_path('imgage'), $picture);
// image uplode function Succesfully saved message
return response()->json(["message" => "Image Uploaded Succesfully"]);
}
else {
return response()->json(["message" => "Select image first."]);
}
}

In Laravel 5.4, you can use guessClientExtension

Related

How to upload multiple image in laravel php

i am trying to upload multiple images in laravel, but it seems only one image in inserted into the database and i was wondering how can i be uploading all images not just one.
here is my controller
public function addProperty(Request $request){
$data = $request->all();
$pModel = new PropertyModel();
return response()->json(["type"=>$pModel->addProperty($data,$request)]);
}
here is my view
<h3>Gallery</h3>
<div class="submit-section">
<div id="selected-files"></div>
<input type="file" name="files[]" multiple onchange="Property.onImageUploadChange(event)" id="files" >
</div>
here is my model
public function addProperty($propertyData,$request){
$db = new Database;
#session_start();
$user = $_SESSION["user"];
$propertyData["user_id"] = $user->user_id;
unset($propertyData["_token"]);
unset($propertyData["property_files"]);
$res = $db->query($db->buildQuery($propertyData, $this->tableName)) or die(false);
$lastID= $db->lastInsertID($res);
$image = $request->file("property_files");
$image->move(public_path('images'),$lastID.".jpg");
return true;
}
may this code help you!
I'm work on backend and use this function:
public static function upload_image($image, $image_folder)
{
$image_new_name = time() . '_' . $image->getClientOriginalName();
$image_path = public_path('uploads\\' . $image_folder);
$image->move($image_path, $image_new_name);
return $image_folder . '/' . $image_new_name;
}
you can create a SettingController and put it there, then in your controller receive array of images and with foreach loop save them in your server like:
foreach($request->arrayImages as $image) {
SettingController::upload_image($image, 'your folder name');
}

Php oop (__construct) file upload

I work on a oop class.php file. I want to implement function __contruct(). I don't know why it doesn't work.
I think there is error, but I don't know how to write it. $args['file_upload'] = $_FILES['file_upload'][''] ?? NULL;
Thanks.
fileupload.class.php
public function __construct($string){
$this->filename = $_FILES['$string']['name']['0'];
$this->temp_path = $_FILES['$string']['tmp_name']['0'];
$this->type = $_FILES['$string']['type']['0'];
$this->size = $_FILES['$string']['size']['0'];
}
public function create() {
if(move_uploaded_file....
}
fileupload.php
if(is_post_request()) {
//Create record using post parameters
$args = [];
$args['prod_name'] = $_POST['prod_name'] ?? NULL;
$args['file_upload'] = $_FILES['file_upload'][''] ?? NULL;
$image = new Imageupload($args);
$result = $image->create();
if($result === true) {
$new_id = $image->id;
$_SESSION['message'] = 'The image was uploaded.';
} else {
// show errors
}
} else {
// display the form
$image = [];
}
<p><input name="file_upload[]" type="file" id="file_upload[]" value=""></p>
<p>Product name: <input type="text" name="prod_name" value="" /></p>
UPDATE1 function works
public function add_files() {
$this->filename = $_FILES['file_upload']['name']['0'];
$this->temp_path = $_FILES['file_upload']['tmp_name']['0'];
$this->type = $_FILES['file_upload']['type']['0'];
$this->size = $_FILES['file_upload']['size']['0'];
}
$image = new Imageupload($args);
$image->add_files();
Looks like you're creating a wheel again? :)
Try one of the libraries has been created for this purpose.
https://github.com/brandonsavage/Upload
Install composer in you operating system and run the following command in your command line
composer require codeguy/upload
Html
<form method="POST" enctype="multipart/form-data">
<input type="file" name="foo" value=""/>
<input type="submit" value="Upload File"/>
</form>
PHP
<?php
$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);
// Optionally you can rename the file on upload
$new_filename = uniqid();
$file->setName($new_filename);
// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$file->addValidations(array(
// Ensure file is of type "image/png"
new \Upload\Validation\Mimetype('image/png'),
//You can also add multi mimetype validation
//new \Upload\Validation\Mimetype(array('image/png', 'image/gif'))
// Ensure file is no larger than 5M (use "B", "K", M", or "G")
new \Upload\Validation\Size('5M')
));
// Access data about the file that has been uploaded
$data = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
// Try to upload file
try {
// Success!
$file->upload();
} catch (\Exception $e) {
// Fail!
$errors = $file->getErrors();
}

why jpg file are saved as tmp in laravel 5.1

I'm trying to upload image in admin panel. but this image is uploading as tmp.
Need I add something other code in my code?
public function store(Request $request)
{
if ($request->hasFile('contents')) {
$destinationPath = 'pictures/SliderImages';
$files = $request->contents;
$file_name = $files->getClientOriginalName();
$files->move($destinationPath, $file_name);
echo "Complete";
} else {
echo "No File";
}
$inputs = $request->all();
$sliders = Sliders::Create($inputs);
return redirect()->action('SliderController#index');
}
this is my blade:
#foreach($sliders as $slider)
<tr>
<td>{{$slider->id}}</td>
<td>{{$slider->title}}</td>
<td><img src="{{$slider->contents}}"></td>
</tr>
#endforeach
this is result in phpmyadmin
try this
$inputs = $request->all();
$inputs['contents'] = $file_name; // add this line in your code
$sliders = Sliders::Create($inputs);
return redirect()->action('SliderController#index');
The $inputs you pass in to Sliders::Create looks to be the original $request parameters? Which probably doesn't include the adjustments you made to that uploaded file.

Laravel Image Update

I'm doing a Admin Panel in Laravel 5.6 and I have a problem where productController --resource update.
My store as this:
if($request->hasfile('filename'))
{
$file = $request->file('filename');
$name=$file->getClientOriginalName();
$image_resize = Image::make($file->getRealPath());
$image_resize->resize(590, 590);
$image_resize->save(public_path('/images/urunler/' .$name));
}
$urun = new Urun();
$urun->k_id=$request->get('k_id');
$urun->ad=$request->get('ad');
$urun->form=$request->get('form');
$urun->icerik=$request->get('icerik');
$urun->ticari_sekli=$request->get('ticari_sekli');
$urun->filename=$name;
$urun->save();
return redirect('/urunler')->with('success','Ürün Başarı İle Eklendi.');
and My Update as this:
$urun= Urun::findOrFail($id);
$urun->update($request->all());
if ($request->hasFile('filename'))
{
$file = $request->file('filename');
$name=$file->getClientOriginalName();
$img = Image::make($file->getRealPath());
$img->resize(590, 590);
$img = Image::make($file->getRealPath())->resize(590, 590)->insert(public_path('/images/urunler/' .$name));
$img->save(public_path('/images/urunler/' .$name));
$urun->image = $name;
}
$urun->save();
return redirect('/urunler')->with('success','Ürün Başarı İle Güncellendi.');
Store part is working but Update part save a filename database but image doesn't move in images/urunler.
My php version is 7.2.4 and I'm using Laravel 5.6.
Delete these codes.
$img = Image::make($file->getRealPath())->resize(590, 590)->insert(public_path('/images/urunler/' .$name));
$img->save(public_path('/images/urunler/' .$name));
After that. Add these codes.
$location = public_path('/images/urunler/'.$name);
Image::make($file->getRealPath())->resize(590, 590)->save($location);
Give it a try.
Solution: Change related codes like that.
$location = public_path('/images/urunler/'.$name);
Image::make($file->getRealPath())->resize(590, 590)->save($location);
$urun->filename= $name;
Then add
$this->validate(request(),[
'k_id' => 'required',
'ad' => 'required',
'form' => 'required',
'icerik' => 'required',
'ticari_sekli' => 'required',
'filename'=>'required' ]);
PS: filename must be just required. Not required|image. It isn't an image. Its just name.
After that request filename. Like that: $urun->filename= $name;
don't $urun->image= $name;. Because there is no $urun->image.
This works for me:
if ($request->file('filename')) {
$file = $request->file('filename');
$destinationPath = $_SERVER['DOCUMENT_ROOT'] . '/images/urunler/';
$file->move($destinationPath, 'FILENAME.' . $file->getClientOriginalExtension());
}
Just edit FILENAME to the name of the file you want or replace FILENAME with $file->getClientOriginalName();
The file wil be saved in the public/images/urunler/ folder
EDIT:
Last thing i can think of would be this: in the form open tag place enctype="multipart/form-data". What this says is that your form exists of normal data AND possible files. There might still be files are not allowed so also place files="true"in the form open.

laravel 5 mime image validation throws exception when uploading an mp3 or mp4

ok.. i don't know how many of you had this problem in Laravel.. i could not find any solution for this.
i'm validating the uploaded image using Validator by setting rules with mime type jpeg, bmp and png.
I flash an error message if it's not of these types.
It works fine for all file types, but when i upload an mp3 or mp4 it shows an exception in my controller.
MyImageController.php Code :
public function addImageDetails()
{
$input = Request::all();
$ID = $input['ID'];
$name = $input['name'];
$file = array('image' => Input::file('image'));
$rules = array('image' => 'required|mimes:jpeg,jpg,bmp,png');
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
\Session::flash('flash_message_error','Should be an Image');
return view('addDetails');
}
else {
//If its image im saving the ID, name and the image in my DB
}
This is the error that i get when i upload an mp3 or mp4
ErrorException in MyImageController.php line 25:
Undefined index: ID
validating all other file types like [.txt, .doc, .ppt, .exe, .torrent] etc..
Once you Allocate the Request::all(); to the variable $input
$input = Request::all();
Then you should check whether it has any value
if (isset($input['ID']))
If the condition satisfies the you shall allow it to proceed further steps else you should return the view with your error message like the code given below.
if (isset($input['ID']))
{
$ID = $input['ID'];
$name = $input['name'];
$file = array('image' => Input::file('image'));
}
else
{
return view('addDetails')->with('message', 'Image size too large');;
}
Update :
Here you check for image type
if (isset($input['ID']))
{
if (Input::file('image'))
{
$ID = $input['ID'];
$name = $input['name'];
$file = array('image' => Input::file('image'));
else
{
return view('addDetails')->with('message', 'Uploaded file is not an image');;
}
}
else
{
return view('addDetails')->with('message', 'Image size too large');;
}
Try with this clean code:
public function addImageDetails(Request request){
$this->validate($request, [
'image' => ['required', 'image']
]);
//If its image im saving the ID, name and the image in my DB
}
There is a rule called image that could be helpful for you in this situation

Categories