Monday, April 8, 2019

How to upload a file in laravel with validation

You can use these step for upload a file in laravel with validation

Step 1 : First of all you create a form with file field.



resources/views/fileupload.php

<?php
echo Form::open(array('url' => '/uploadfile','files'=>'true'));
echo 'Select the file to upload.';
echo Form::file('image');
echo Form::submit('Upload File');
echo Form::close();
?>


Step 2 : Define route in routes file



app/Http/routes.php.


Route::get('/uploadfile','UploadFileController@index');
Route::post('/uploadfile','UploadFileController@showUploadFile');

Step 3 : Create a controller




app/Http/Controllers/UploadFileController.php file.



<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UploadFileController extends Controller {
public function index() {
return view('uploadfile');
}
public function showUploadFile(Request $request) {

$validator = Validator::make($request->all(), [
                'image' => 'max:2048|mimes:jpg,jpeg,gif,png']);

              if ($validator->fails()) {
                   return redirect('/')
                               ->withErrors($validator)
                               ->withInput();
                    }
else{



$file = $request->file('image');
//Display File Name
echo 'File Name: '.$file->getClientOriginalName();
echo '<br>';
//Display File Extension
echo 'File Extension: '.$file->getClientOriginalExtension();
echo '<br>';
//Display File Real Path
echo 'File Real Path: '.$file->getRealPath();
echo '<br>';
//Display File Size
echo 'File Size: '.$file->getSize();
echo '<br>';
//Display File Mime Type
echo 'File Mime Type: '.$file->getMimeType();
//Move Uploaded File
$destinationPath = 'uploads';
$file->move($destinationPath,$file->getClientOriginalName());
}
}
}
Now to can run own url for upload a file in laravel with validation

http://localhost:8000/uploadfile

No comments:

Post a Comment