This post is also available in:
English
Hallo apa kabar semuanya, semoga sehat dan bahagia selalu.
Kali ini kita akan membahas laravel, yaitu kita akan membuat cara upload file menggunakan jQuery ajax. dan bagaimana cara upload file ke database MySQL dan server folder dengan validasi. kita akan upload file dengan format image jpg dan png.
Kalian dapat mempelajari tutorial yang lainnya:
Tutorial Laravel : Push Notification Dengan Firebase Laravel 9
Tutorial Laravel : Membuat Dynamic Dependent Dengan Select2
Tutorial Laravel ~ Laravel Eloquent Relationships
1. Download Laravel
composer create-project --prefer-dist laravel/laravel Blog
2. Add Database Credentials
Selanjutnya, Navigasikan ke direktori root aplikasi laravel yang Anda unduh dan buka file .env. Kemudian tambahkan detail database Anda di file .env, sebagai berikut:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here
3. Generate Migration & Model
buka command prompt dan jalankan perintah berikut:
php artisan make:model document -m
Kemudian Navigasikan ke folder database/migrations dan buka create_documents_table.php. Kemudian perbarui kode berikut ke create_documents_table.php:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatedocumentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('documents', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('documents');
}
}
php artisan migrate
3. Controller
Buat sebuah file controller PageController
php artisan make:controller PageController
Buatlah 2 buah methods.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Document;
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()->first('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->move($location,$filename);
// File path
$filepath = url('files/'.$filename);
$document = new Document();
$document->title = $file;
$document->save();
// Response
$data['success'] = 1;
$data['message'] = 'Uploaded Successfully!';
$data['filepath'] = $filepath;
$data['extension'] = $extension;
}else{
// Response
$data['success'] = 2;
$data['message'] = 'File not uploaded.';
}
}
return response()->json($data);
}
}
4. Route
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PageController;
Route::get('/', [PageController::class, 'index']);
Route::post('/uploadFile', [PageController::class, 'uploadFile'])->name('uploadFile');
5. View
<!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-8">
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style type="text/css">
.displaynone{
display: none;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<!-- Response message -->
<div class="alert displaynone" id="responseMsg"></div>
<!-- File preview -->
<div id="filepreview" class="displaynone" >
<img src="" class="displaynone" with="200px" height="200px"><br>
<a href="#" class="displaynone" >Click Here..</a>
</div>
<!-- Form -->
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">File <span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type='file' id="file" name='file' class="form-control">
<!-- Error -->
<div class='alert alert-danger mt-2 d-none text-danger' id="err_file"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input type="button" id="submit" value='Submit' class='btn btn-success'>
</div>
</div>
</div>
</div>
</div>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.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(){
// Get 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: 'post',
data: fd,
contentType: false,
processData: false,
dataType: 'json',
success: function(response){
// Hide error container
$('#err_file').removeClass('d-block');
$('#err_file').addClass('d-none');
if(response.success == 1){ // 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').show();
}
}else if(response.success == 2){ // File not uploaded
// Response message
$('#responseMsg').removeClass("alert-success");
$('#responseMsg').addClass("alert-danger");
$('#responseMsg').html(response.message);
$('#responseMsg').show();
}else{
// Display Error
$('#err_file').text(response.error);
$('#err_file').removeClass('d-none');
$('#err_file').addClass('d-block');
}
},
error: function(response){
console.log("error : " + JSON.stringify(response) );
}
});
}else{
alert("Please select a file.");
}
});
});
</script>
</body>
</html>
6. Run
php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080
Demikian tutorial kali ini saya buat, semoga bermanfaat.
Terimakasih.