My Laravel version is 5.6.and PHP is 7.
I found some upload sample on the internet, but most of them do not work.
Have anyone can provide a complete example to me?
I found a similar case on the Internet.
Laravel 5.6 Excel and CSV import export using maatwebsite example
Unfortunately, it doesn't work, too.
Here is my source code.
blade.php
<form class="form-upload" method="POST" action="{{url('/excelUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="file">excel upload</label>
<input type="file" id="file" name="ex_file">
<p class="help-block">!!!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default">cancel</button>
<button type="submit" class="btn btn-primary" id="upload_f">submit</button>
controller.php
public function excelUpload(Request $request){
if($request->hasFile('StudentUploadSample')){
return "yes i have a file";
}
return "nofile";
}
However, the result always show "nofile".
I didn't use any "use". Should I use something?
The example on the web page does not use any "use", too.
In addition, I read some of the websites that the files will be placed under the storage folder, but I can't find my file "StudentUploadSample.xlsx" in the storage folder.
Have anyone can provide a complete example to me or how to solve this problem?
Replace the name of file and use the reference site where you will get the proper code with explanation.
Reference site like: http://www.expertphp.in/article/laravel-5-maatwebsite-import-excel-into-db-and-export-data-into-csv-and-excel
public function importFileIntoDB(Request $request){
if($request->hasFile('sample_file')){
$path = $request->file('sample_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['name' => $value->name, 'details' => $value->details];
}
if(!empty($arr)){
\DB::table('products')->insert($arr);
dd('Insert Record successfully.');
}
}
}
dd('Request data does not have any files to import.');
}
You use the wrong name of the file in your controller:
if($request->hasFile('ex_file')){
return "yes i have a file";
}
So fix that, and try to check.
replace <input type="file" id="file" name="ex_file"> with <input type="file" id="file" name="StudentUploadSample">
and you are done.
you can use laravel excel.
address:https://github.com/Maatwebsite/Laravel-Excel
/**
* my Controller code
*
*/
$updateFile = $request->file('update_file');
$fileSize = (int) filesize($updateFile);
$fileExtension = $updateFile->getClientOriginalExtension();
$filePath = $updateFile->getRealPath();
$excelData = Excel::load($filePath)->get()->toArray();
or you can use: https://phpspreadsheet.readthedocs.io/en/develop/
Related
Hi im new to laravel 9 and im trying to upload file from view to controller, but somehow the input file didnt pass the file to controller.
im using laravel 9 with boostrap in it.
heres my code :
view
<form enctype="multipart/form-data" action="{{ route('profile.put') }}" method="POST">
#csrf
#method('POST')
<div class="card-body">
<input id="file" name="file" type="file">
<button type="submit" class="btn btn-block btn-primary">{{ __('Save') }}</button>
</div>
</form>
controller
public function put(Request $request){
return $request;
}
i try to see the $request variable but the result is like this
enter image description here
i try the solution like add enctype="multipart/form-data" but still didnt work.
thank you in advance
I think you simply should get the request by its name or using `$request->all()`, you can do these two things:
In your controller you should write your put method like below:
public function put(Request $request){
$file = '';
if($request->file('file'))
{
$file = $request->get('file);
}
return $file;
}
or you can use the below code in your put method
public function put(Request $request){
return $request->all();
}
Note: If you don't send the file as a JSON Response you should return it to view after saving operation;
and also, there is no need to put #method('POST') inside the form;
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');
}
I'm working on the database restore menu for an application I created, I'm using sqlite for my database, and I want to put my previously backed up database file to the database directory
backupAndRestore.blade.php
<form method="POST" action="/admin/backupAndRestore/restore" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="file-field input-field">
<div class="btn">
<span><i class="material-icons">file_upload</i></span>
<input type="file" name="database" accept=".sqlite">
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path" placeholder="Example: file_name.sqlite" readonly>
</div>
</div>
<button type="submit" class="btn">restore</button>
</form>
web.php
Route::post('/admin/backupAndRestore/restore', 'DatabaseController#restore');
DatabaseController.php
public function restore(Request $request)
{
$database = $request->database;
$file_name = 'database2.sqlite';
$path = database_path($file_name);
file_put_contents($path, $database);
return $path;
}
my code works, the file is stored in the database directory, the problem is when I backup my database file size is 22kb, but when I restore it and I check the database directory, the file is 1kb size and when I open using sublime file contents as shown below
Images
which I expect as shown below
Images
can someone tell where my fault is?
You are using file_put_contents which inserts the contents in the given file and does not move the file.
If you want to store a file in database path..
public function restore(Request $request)
{
$this->validate($request, [
'database' => 'required|file|mimes:sqlite'
]);
$databaseFile = $request->database;
$fileName = 'database2.sqlite';
$databaseFile->move(database_path(), $fileName);
// return success message...
}
For more information uploading files: https://laravel.com/docs/5.4/requests#files.
I want to upload file in my app.
This is the blade file .
<form action="/fileUploader " files="true" method="post" role="form" name="file" id="chan" >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="panel panel-default">
<label>Please Select a File to Upload</label>
<input type="image">
<button type="submit" name ="Upload_File">Upload File</button>
</div>
</form>
This is my controller file
public function viewFile()
{
return View::make('/fileUploader');
}
public function showfileupload(Request $request)
{
$file = $request -> file('image');
// show the file name
echo 'File Name : '.$file->getClientOriginalName();
echo '<br>';
// show file extensions
echo 'File Extensions : '.$file->getClientOriginalExtension();
echo '<br>';
// show file path
echo 'File Path : '.$file->getRealPath();
echo '<br>';
// show file size
echo 'File Size : '.$file->getSize();
echo '<br>';
// show file mime type
echo 'File Mime Type : '.$file->getMimeType();
echo '<br>';
// move uploaded File
$destinationPath = 'uploads';
$file->move($destinationPath,$file->getClientOriginalName());
}
This is the web.php file
Route::get('/fileUploader', 'channelController#viewFile');
Route::post('/fileUploader', 'channelController#showfileupload');
I'm getting an error called FatalThrowableError in channelController.php line 48:
Call to a member function getClientOriginalName() on null.
How can I solve this problem
Most likely, you are trying to call a method - getClientOriginalName() - on a object that doesn't exist, so it's null. That jives with the error message you are seeing.
I'm not sure why, but we can start working backwards. Let's use an if statement with the hasFile() method to verify that a file is actually present on the request before attempting to move() it.
if ($request->hasFile('image')) {
$file->move($destinationPath,$file->getClientOriginalName());
}
If you implement the above, does the error still exist?
Here are the Laravel 5.3 Docs on file uploads. It may give you some more ideas.
If you're finding that users are posting files and hasFile() is still returning boolean FALSE, then you may want to go digging into the php.ini file and take a look at the Post_max_size or upload_max_size values to make sure that we aren't blocking large uploads.
VIEW
{!! Form::open(['route'=>'fileUploader', 'id'=>'chan', 'files' => true] )!!}
<div class="panel panel-default">
<label>Please Select a File to Upload</label>
<input type="file" name="image">
<button type="submit">Upload File</button>
</div>
{!! Form::close()!!}
ROUTES
Route::get('/fileUploader', 'channelController#viewFile');
Route::post('fileUploader', array(
'as' => 'fileUploader',
'uses' => 'channelController#showfileupload',
));
CONTROLLER
public function showfileupload(Request $request){
$file = $request -> file('image');
dd($file); // This work well for me and return information about the image
}
Do copy and past! i hope it work, let me know any error and result!