Laravel 8 Single Ajax File Upload With Validation.



Make Directory Structure
- database
- public
- filebox
- profile
- 1643820454_568_1001.jpg
- 1643820616_941_1001.jpg
- 1643820658_331_1001.jpg
- resouces

config\filesystems.php
'disks' => [
        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],
        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],
        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
            'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        ],
        'filebox_profile' => [
            'driver' => 'local',
            'root' => public_path('filebox/profile'),
            'url' => env('APP_URL').'filebox',
            'visibility' => 'public',
        ],

    ],

web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FlightController;
Route::get('/', function () {
    return view('welcome');
});
Route::get('/flight-create',[FlightController::class,'create'])->name('flight.create');
Route::post('/flight-store',[FlightController::class,'store'])->name('flight.store');
Route::get('/flight-image-upload',[FlightController::class,'imageUpload'])->name('flight.image-upload');
Route::post('/flight-image-upload-save',[FlightController::class,'imageUploadSave'])->name('flight.image-upload-save');

HTML Blade:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Flight Image Upload</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-4">
                <div class="mb-3">
                    <label for="imageUpload" class="form-label">Image Upload</label>
                    <input type="file" class="form-control form-control-sm image_type" name="image_upload" id="image-upload">
                    <p id="preview-image"></p>
                    <p id="message"></p>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function() {
            $('body').on('change','.image_type',function(){
                let image_upload= $('#image-upload')[0];
                let formData = new FormData();
                formData.append('image_files', image_upload.files[0]);
                formData.append('_token', '{{ csrf_token() }}');
                formData.append('category_type', 'profile'); // extra paramter.
                $.ajax({
                    url: "{{ route('flight.image-upload-save') }}",
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false
                })
                .done(function(resp) {
                    if(resp.success) {
                        $('#preview-image').text(resp.data);
                        $('#message').text(resp.message);
                    } else {
                        $('#preview-image').text(resp.data);
                        $('#message').text(resp.message);
                    }
                })
                .fail(function() {
                })
                .always(function() {
                });
            });
        });// Close jQuery
    </script>
</body>
</html>

FlightController:
<?php
namespace App\Http\Controllers;
use App\Models\Flight;
use Illuminate\Http\Request;
use App\Http\Requests\StoreFlightRequest;
use App\Http\Requests\UpdateFlightRequest;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
class FlightController extends Controller {
    public function index() {
    }
    public function create() {
        return view('flight.create');
    }
    public function store(StoreFlightRequest $request) {
        $postData = $request->validated();
        dd($postData);
    }
    public function show(Flight $flight) {
    }
    public function edit(Flight $flight) {
    }
    public function update(UpdateFlightRequest $request, Flight $flight) {
    }
    public function destroy(Flight $flight){
    }
    public function imageUpload() {
        return view('flight.file_upload');
    }
    public function imageUploadSave(Request $request) {
        $postData = $request->all();
        $validator = Validator::make($request->all(), [
            'image_files' => 'required|mimes:jpg,png,jpeg,gif|max:2048'
        ]);
        if ($validator->fails()) {
            return response()->json(['success'=>false, 'message'=> "File format invalid", "data" => ""]);
        }
        $file                           = $request->file('image_files');
        $mime_type                      = $file->getClientMimeType();
        $extension                      = $file->getClientOriginalExtension();
        $imageName                      = $file->getClientOriginalName();
        $newFile                        = time().'_'.rand(100,999).'_'.$imageName;
        $filePath                       = "filebox/profile/";
        Storage::disk('filebox_profile')->put($newFile, fopen($file,'r+'));
        return response()->json(['success'=>true, "message" => 'Image uploaded', 'data' => $newFile]);
    }


private function _imageMoved() {
$folderPathName = "filebox/"."profile";
if (!File::exists($folderPathName)) {
File::makeDirectory($folderPathName, 0777, true, true);
}
$folderPathName = $folderPathName.'/'.$row['file_name'];
$tempPathName = "filebox/temp_images/"."1643820454_568_1001.jpg";
if(File::exists($tempPathName)) {
File::move($tempPathName, $folderPathName);
}
}
}


Note: How Delete Files
$directoryPath     = "filebox/profile/"."1643820454_568_1001.jpg";
if (File::exists($directoryPath)) {
File::delete($directoryPath);
}
Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment