How to Get the Name of the Uploaded File in Jquery and Print It
Using AJAX y'all can upload a file to the server without reloading the folio.
Require to send CSRF token with AJAX request to upload the file.
In this tutorial, I testify how you can upload a file using jQuery AJAX and display preview in Laravel 8.
Contents
- Controller
- Road
- View
- Output
- Conclusion
1. Controller
Create a PageController controller.
php artisan make:controller PageController
Create two methods –
- index() – Load
alphabetizeview. - uploadFile() – This method is used to upload the file.
Create $data Array to store render response.
Define file validation. I set the max file size to 2 MB (2048 Kb).
If the file is non validated then assign 0 to $data['success'] and validation response to $data['error'].
If the file is validated so assign file name to $filename and file extension to $extension variable. Assign upload location "files" to $location variable.
Execute$file->motility($location,$filename); to store the file.
Assign ane to $data['success'], 'Uploaded Successfully!' to $data['message'], file path to $information['filepath'], and file extension to $data['extension'].
If the file is not uploaded then assign2 to $information['success'] and 'File non uploaded.' bulletin to $data['bulletin'].
Return $data Array in JSON format.
Completed Code
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class PageController extends Controller { public function index(){ return view('index'); } public function uploadFile(Request $request){ $data = array(); $validator = Validator::make($request->all(), [ 'file' => 'required|mimes:png,jpg,jpeg,csv,txt,pdf|max:2048' ]); if ($validator->fails()) { $data['success'] = 0; $data['error'] = $validator->errors()->offset('file');// Error response }else{ if($request->file('file')) { $file = $request->file('file'); $filename = time().'_'.$file->getClientOriginalName(); // File extension $extension = $file->getClientOriginalExtension(); // File upload location $location = 'files'; // Upload file $file->motility($location,$filename); // File path $filepath = url('files/'.$filename); // Response $information['success'] = i; $information['message'] = 'Uploaded Successfully!'; $data['filepath'] = $filepath; $data['extension'] = $extension; }else{ // Response $data['success'] = ii; $data['bulletin'] = 'File not uploaded.'; } } render response()->json($information); } } 2. Route
- Open
routes/web.phpfile. - Define 2 routes –
- / – Load index view.
- /uploadFile – This use to upload a file using AJAX.
Completed Code
<?php use Illuminate\Support\Facades\Route; apply App\Http\Controllers\PageController; Route::go('/', [PageController::grade, 'index']); Road::postal service('/uploadFile', [PageController::form, 'uploadFile'])->name('uploadFile'); 3. View
Create alphabetize.blade.php file in resources/views/.
Stored CSRF token in the <meta > tag.
Display file upload response bulletin in <div id="responseMsg"> using jQuery.
Created<img > and<a > element in<div id="filepreview"> to display a file preview co-ordinate to the file extension using jQuery.
Create a file element and a button. Brandish error in <div id="err_file"> if file not validated using jQuery.
Script
Read CSRF token from <meta > tag and assign to CSRF_TOKEN variable.
On the push button click read the selected file and assign to files variable.
If file not selected so alarm("Please select a file."); otherwise, laissez passer the selected file using FormData object. Also, pass CSRF_TOKEN with FormData.
Send AJAX POST request to"{{route('uploadFile')}} where pass FormData Object as data.
On successful callback cheque upload condition.
Ifresponse.success == ane means file successfully uploaded. Display the response message and preview the file co-ordinate to the file extension.
Ifresponse.success == 2 ways file is non uploaded. Brandish the response message.
Ifresponse.success does non equal 1 or 2 means the file is not validated. Brandish the error message.
Completed Code
<!DOCTYPE html> <html> <head> <title>How to upload a file using jQuery AJAX in Laravel 8</title> <!-- Meta --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-eight"> <meta charset="utf-8"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/iv.5.2/css/bootstrap.min.css"> <fashion type="text/css"> .displaynone{ brandish: none; } </way> </head> <torso> <div class="container"> <div class="row"> <div course="col-physician-12 col-sm-12 col-xs-12"> <!-- Response message --> <div class="alarm displaynone" id="responseMsg"></div> <!-- File preview --> <div id="filepreview" class="displaynone" > <img src="" class="displaynone" with="200px" acme="200px"><br> <a href="#" form="displaynone" >Click Here..</a> </div> <!-- Form --> <div class="form-group"> <characterization class="control-characterization col-doc-3 col-sm-3 col-xs-12" for="name">File <bridge form="required">*</bridge></label> <div class="col-dr.-6 col-sm-six col-xs-12"> <input type='file' id="file" name='file' course="course-control"> <!-- Error --> <div class='alert alert-danger mt-two d-none text-danger' id="err_file"></div> </div> </div> <div form="form-group"> <div form="col-medico-6"> <input blazon="push" id="submit" value='Submit' class='btn btn-success'> </div> </div> </div> </div> </div> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.five.1/jquery.min.js"></script> <script type="text/javascript"> var CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]').getAttribute("content"); $(document).ready(function(){ $('#submit').click(function(){ // Become the selected file var files = $('#file')[0].files; if(files.length > 0){ var fd = new FormData(); // Append data fd.append('file',files[0]); fd.append('_token',CSRF_TOKEN); // Hide alert $('#responseMsg').hide(); // AJAX request $.ajax({ url: "{{route('uploadFile')}}", method: 'mail', data: fd, contentType: simulated, processData: false, dataType: 'json', success: role(response){ // Hide fault container $('#err_file').removeClass('d-cake'); $('#err_file').addClass('d-none'); if(response.success == i){ // Uploaded successfully // Response message $('#responseMsg').removeClass("alert-danger"); $('#responseMsg').addClass("alert-success"); $('#responseMsg').html(response.message); $('#responseMsg').show(); // File preview $('#filepreview').show(); $('#filepreview img,#filepreview a').hide(); if(response.extension == 'jpg' || response.extension == 'jpeg' || response.extension == 'png'){ $('#filepreview img').attr('src',response.filepath); $('#filepreview img').show(); }else{ $('#filepreview a').attr('href',response.filepath).show(); $('#filepreview a').bear witness(); } }else if(response.success == 2){ // File not uploaded // Response message $('#responseMsg').removeClass("warning-success"); $('#responseMsg').addClass("alarm-danger"); $('#responseMsg').html(response.message); $('#responseMsg').show(); }else{ // Display Mistake $('#err_file').text(response.error); $('#err_file').removeClass('d-none'); $('#err_file').addClass('d-block'); } }, error: part(response){ panel.log("fault : " + JSON.stringify(response) ); } }); }else{ alert("Delight select a file."); } }); }); </script> </body> </html> iv. Output
View Output
5. Conclusion
Apply the FormData object if you want to pass extra data while sending AJAX request e.m. – fd.append('filename',"file 1");. Hither, fd is FormData object.
Make sure to bank check upload_max_filesize and post_max_size values in the php.ini file if you are assuasive large files to upload.
You tin can view this tutorial to know file upload without jQuery AJAX.
If you found this tutorial helpful then don't forget to share.
Related posts:
Source: https://makitweb.com/how-to-upload-a-file-using-jquery-ajax-in-laravel-8/
0 Response to "How to Get the Name of the Uploaded File in Jquery and Print It"
Post a Comment