---
description: https://www.nicesnippets.com/blog/how-to-upload-file-using-ajax-in-laravel-9
---

# How to Upload File using Ajax Phần 1 (ok)

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2F3qbibhSuvY9mMkyZQzpH%2Fimage.png?alt=media&#x26;token=930be3ee-177e-4ba0-8916-ea74afdcf0a1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2Frs4Ab0ECRlN9ANwKdtDN%2Fimage.png?alt=media&#x26;token=a7ce4a4a-4348-4cb5-828b-0d92d6e366d4" alt=""><figcaption></figcaption></figure>

C:\xampp8\htdocs\datvietcoconut\routes\web.php

```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
<?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
<?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
<?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

```blade
<!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>

```

