I've looked at code from other people and try to implement the same thing, but the application could not store the image to the desire folder, would you please have a look at what the reason is? Thank you!
Here is my code for route:
Route::post('upload_pic', 'UploadController#storePhoto');
Here is my code for the php laravel template:
<div class="panel-body">
<form action="{{url('/upload_pic')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="upload-user-photo">Upload Photos</label>
<input type="file" name="image" class="form-control" placeholder="Upload Student Image, Size:207(W)x408(H)">
</div>
<div class="row">
<div class="col-sm-4">
<input class="btn btn-success" type="submit" value="Upload Student Photo" name="submit">
</div>
</div>
</form>
</div>
Here is my code in the controller:
public function storePhoto(Request $request){
$valid = $request->validate([
'image' => 'required|image|mimes:jpg,png,jpeg,|dimensions:max_width=272,max_height=408,min_width=271,min_height=407'
]);
$data = new Postimage();
$file = $request->file('image');
$filename = $file->getClientOriginalName();
// dd($filename);
$file -> move(public_path('./public/img/student_photos'),$filename);
$data['image'] = $filename;
$data->save();
return redirect('/upload')->with('success', 'Photo Uploaded');
}
Your problem is somewhere here
$filename = $file->getClientOriginalName();
$file -> move(public_path('./public/img/student_photos'),$filename);
First, the file comprises only the file extension. Instead, you should have something like this $filename = 'name.' . $file->getClientOriginalName(); Notice the dot in 'name.'
Secondly, no need to add public to the file path string. So it should be $file->move(public_path('img/student_photos'),$filename);
Finally, make sure the upload folder exists and is writeable
Related
Here is my controller
public function createAdmin()
{
$photo=$_FILES['bannerPic']['name'];
$tempname=$_FILES['bannerPic']['tmp_name'];
// echo $tempname." ".$photo;
move_uploaded_file($tempname, 'picture/banner/'.$photo);
$data=[
'sliderPic' => $photo,
];
dd($data);
// \App\Models\Banner::create($data);
// return view('Banner');
}
here is my route
Route::post('/BannerEdit', [App\Http\Controllers\BannerController::class,
'createAdmin']);
here is my blade form
<form action="{{ url('') }}/BannerEdit" method="post" class="col-12"
enctype="multipart/form-data">
#csrf
<div class="mb-3 col-12">
<label class="col-4 text-label form-label">Banner Photo*</label>
<input type="file" name="bannerPic" class="form-control input-rounded col-4 mb-3"
required>
</div>
<div class="mb-3 text-end">
<input type="submit" class="btn btn-primary" value="Upload">
</div>
</form>
When i submit the data it Gives me an Error as
move_uploaded_file(picture/banner/favicon.jpg): Failed to open stream: No such file or directory
But this Directory Exists
And i checked with full pathof localhost then it does not supports http path
You need to use getcwd() function like this:
$dirpath = realpath(dirname(getcwd()));
So your controller code will be:
public function createAdmin()
{
$photo=$_FILES['bannerPic']['name'];
$tempname=$_FILES['bannerPic']['tmp_name'];
// echo $tempname." ".$photo;
$dirpath = realpath(dirname(getcwd()));
move_uploaded_file($tempname, $dirpath.'/'.$photo);
$data=[
'sliderPic' => $photo,
];
dd($data);
// \App\Models\Banner::create($data);
// return view('Banner');
}
let me know if it works.. if not then we'll modify $dirpath variable
PS: this solution will work on server. are you working on server or in localhost?
EDIT:
Other solution is to use below function to get proper directory structure:
$dirpath = public_path('picture/banner/');
When I am uploading an image to the form and returning it from the controller, the image name and extention are changing.I am a beggar, so if I make a mistake while asking a question, I would like to apologize.
This is my form:
<form action="{{ route('admin.slider.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<label class="control-label">Image</label>
<input type="file" name="image">
</div>
</div
<button type="submit" class="btn btn-success">Save</button>
</form>
This is my controller:
public function store(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,bmp,png,jpg',
]);
$image = $request->file('image');
return $image;
}
My image file name is :demo.jpg
Controller return result is like that:
C:\xampp\tmp\php5E86.tmp
This is the same result when I give another picture, only the last four characters are changing.
C:\xampp\tmp\phpF239.tmp
It is very helpful to know why I am getting .tmp file return.
use getClientOriginalName to get orginal file name
$request->image->getClientOriginalName()
To get file extension
$request->image->extension();
or
$name = $request->file('image')->getClientOriginalName();
$extension = $request->file('image')->extension();
Ref:https://laravel.com/docs/8.x/filesystem#other-uploaded-file-information
I was working on a project and was trying to develop a file uploading system for skins.
When I tried to upload my skin, I was given "Call to a member function storeAs() on null"
public function uploadSkin(Request $request)
{
/* $request->validate([
'skins' => 'required|mimes:png|max:1024',
]); */
$storage_dir = storage_path('app/skins');
$request->file('skins')->storeAs($storage_dir, Auth::user->name . '.png');
return route('settings')->with('success', 'skin uploaded :)');
}
Form code:
<form method="post" enctype="multipart/form-data" action="/settings">
#csrf
<br/>
<div class="form-group">
<input type="file" class="form-control-file" id="skins" name="skins" required>
</div>
<button type="submit" class="btn btn-success">Upload</button>
</form>
To store a file like an image or any kind of files you can use a code like this:
public function uploadSkin(Request $request){
$image = $request->file('skins');
if ($image != null) {
$image->move('uploads/skins/', Auth::user()->name . $image->getClientOriginalExtension());
}
return route('settings')->with('success', 'skin uploaded :)');
}
To uppload a file there are various ways in the laravel but for now you can try this to simply move your file to your directory:
if($files= $request->file('skins')){
$files->move('uploads/skins/', Auth::user->name . '.png');
}
In add employee form I have to upload profile pic?
is this code is valid??
will anyone help me to modify the code?
This Code Is In My Controller File
$employee = new User();
$file = $request->file('file');
$name = time() . $file->getClientOriginalName();
$file->move('uploads/images', $
$employee->file = $file;
$employee->save();
This IS Code Of My view file
<div class="col-md-6">
<div class="form-group">
<label for="photo">Profile Picture :<span class="danger">*</span> </label>
<input type="file" class="form-control" id="file" name="file">
</div>
</div>
Issue is that everything work properly but in my collection of mongodb file isn't store. it upload in folder, but not in database.
You should change $file variable with $name
$employee->file = $name; // $file may contain file object
$employee->save();
I am trying to implement a image upload with other form elements with dropzone.js in laravel. So far I've managed to display the drag and drop image upload view with other form elements. And also get POST details from the submitted form. But when dropzone is passing the uploaded image to the database data save function it encode image with base64. I think I've managed to get the file extension also. And when I submit the button it gives me this error "Call to a member function move() on string" . Please put me in the right direction.
Here is the Form
<form class="form-horizontal" action="{{ route('save-slider-content') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderTitle" id="sliderTitle" placeholder="Title of the post goes here">
</div>
</div>
<input type="hidden" name="date" id="date" value="<?php echo date("d-m-Y"); ?>">
<div class="form-group">
<label for="image" class="col-sm-2 control-label">Image</label>
<input hidden id="file" name="file"/>
<div class="col-sm-10">
<div class="dropzone needsclick dz-clickable" id="fileUpload">
<div class="dz-default dz-message">
<i class="fa fa-image fa-5x"></i>
<h3 class="sbold">Drop an image here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Link</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderLink" id="sliderLink" placeholder="Provide a link">
</div>
</div>
</div><br>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Post</button>
</div>
<!-- /.box-footer -->
</form>
Here is the dropzone configuration
<script type="text/javascript">
Dropzone.options.fileUpload = {
url: "save-slider-content",
addRemoveLinks: true,
accept: function(file) {
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function() {
let content = fileReader.result;
$('#file').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
}
</script>
Route
Route::post('store-slider-content', [ 'as' => 'save-slider-content', 'uses' => 'SliderContent#save_slider_data']);
save_slider_data function in Controller
public function save_slider_data(Request $request)
{
$slider = new Slider;
$slider->title = $request->sliderTitle;
$slider->title_sin = $request->sliderTitleSin;
$slider->date = $request->date;
$slider->link = $request->sliderLink;
$file = $request->file;;
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$f = finfo_open();
$mime_type = finfo_buffer($f, $image_data, FILEINFO_MIME_TYPE);
$imageName = time().'.'.$mime_type;
$image_data->move(public_path('slider_uploads'), $imageName);
return response()->json(['success'=>$imageName]);
$slider->img_url = $imageName;
$slider->save();
}
Edited to include the logic for either Symfony\Component\HttpFoundation\File\File or Illuminate\Support\Facades\File (Illuminate\Filesystem\Filesystem)
move is a method of a File object, but $image_data is just a string. So one thing you could do is write the decoded image to a temp file, instantiate a File of it, and move it, like
//... your code ...
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
// ... and then:
//grab a new tmp file
$tmpFilePath=sys_get_temp_dir().'/'.uniqid();
//write the image to it
file_put_contents($tmpFilePath, $image_data);
//move it.
//give it a name
$imageName = time().'.'.str_replace("image/","",$mime_type);
//if using Symfony\Component\HttpFoundation\File\File;
//get an instance of File from the temp file and call ->move on it
$tmpFile=new File($tmpFilePath);
$tmpFile->move(public_path('slider_uploads'), $imageName);
//or if using File facade
File::move($tmpFilePath, public_path("slider_uploads/$imageName"));
//...and then, back to your code...
$slider->img_url = $imageName;
$slider->save();
return response()->json(['success'=>$imageName]);
}
You can do this:
In config/filesystems.php, register a new disk slider_uploads
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'slider_uploads' => [
'driver' => 'local',
'root' => public_path('slider_uploads')
]
]
And then use your new disk in storing your image
$image_data = $request->file;
#list($type, $image_data ) = explode(';', $image_data );
#list(, $image_data ) = explode(',', $image_data );
if($image_data !=""){ // storing image in public/slider_uploads/ Folder
\Storage::disk('slider_uploads')->put($imageName, base64_decode($image_data ));
}