🥳How to Upload File using Ajax Phần 1 (ok)
https://www.nicesnippets.com/blog/how-to-upload-file-using-ajax-in-laravel-9


C:\xampp8\htdocs\datvietcoconut\routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUploadController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(FileUploadController::class)->group(function () {
Route::get('file-upload', 'create')->name('file.create');
Route::post('file-upload', 'store')->name('file.store');
});
C:\xampp8\htdocs\datvietcoconut\app\Models\File.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory;
protected $table = 'images';
protected $fillable = [
'name'
];
}
C:\xampp8\htdocs\datvietcoconut\database\migrations\2023_02_06_150050_create_images_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
};
C:\xampp8\htdocs\datvietcoconut\app\Http\Controllers\FileUploadController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileUploadController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('files.create');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'file' => 'required|mimes:doc,docx,pdf,zip,rar,jpg,png|max:2048',
]);
$fileName = time() . '.' . $request->file->extension();
$request->file('file')->storeAs('files', $fileName, 'public');
File::create(['name' => $fileName]);
return response()->json('File uploaded successfully');
}
}
C:\xampp8\htdocs\datvietcoconut\resources\views\files\create.blade.php
<!DOCTYPE html>
<html>
<head>
<title>How to Upload File using Ajax in Laravel 9? - Nicesnippets.com</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="panel panel-primary card mt-5">
<div class="panel-heading text-center mt-4">
<h2>How to Upload File using Ajax in Laravel 9? - Nicesnippets.com</h2>
</div>
<div class="panel-body card-body">
<form action="{{ route('file.store') }}" method="POST" id="file-upload" enctype="multipart/form-data">
@csrf
<div class="mb-3">
<label class="form-label" for="inputFile">Select File:</label>
<input type="file" name="file" id="inputFile" class="form-control">
<span class="text-danger" id="file-input-error"></span>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#file-upload').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#file-input-error').text('');
$.ajax({
type: 'POST'
, url: "{{ route('file.store') }}"
, data: formData
, contentType: false
, processData: false
, success: (response) => {
if (response) {
this.reset();
alert('File has been uploaded successfully');
}
}
, error: function(response) {
$('#file-input-error').text(response.responseJSON.message);
}
});
});
</script>
</html>
Previous😒 Download File from URL to Storage Example, Download File From URL to Public Storage Folder (ok)NextHow to Upload File using Ajax Phần 2 (ok)
Last updated
Was this helpful?