😅How to Upload File using Ajax Phần 3 (use change) (ok)

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

<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
use App\Http\Controllers\PageController;
Route::get('/', [PageController::class, 'index']);
Route::post('/uploadFile', [PageController::class, 'uploadFile'])->name('uploadFile');

C:\xampp8\htdocs\datvietcoconut\resources\views\index.blade.php

<!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">
        <form method="POST" enctype="multipart/form-data" id="upload_form">
          @csrf
          <input type="file" name="file" id="file">
        </form>
      </div>
    </div>
  </div>
  <!-- Script -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    function uploadfile() {
      var CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]').getAttribute("content");
      var formData = new FormData();
      var files = $('#file')[0].files;
      formData.append('file', files[0]);
      formData.append('_token', CSRF_TOKEN);
      $.ajax({
        type: 'POST'
        , url: "{{ route('uploadFile') }}"
        , data: formData
        , contentType: false
        , processData: false
        , success: (response) => {
          if (response) {
            alert('Image has been uploaded successfully');
          }
        }
        , error: function(response) {
          console.log(response);
        }
      });
    }
    $("#file").change(function() {
      uploadfile();
    });
  </script>
</body>
</html>

C:\xampp8\htdocs\datvietcoconut\app\Http\Controllers\PageController.php

<?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)
  {
    $request->validate([
      'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);
    if ($request->hasFile('file')) {
      $image = $request->file('file');
      $getName = $image->getClientOriginalName();
      $imageName = time() . $getName;
      $destinationPath = public_path('/uploads');
      $image->move($destinationPath, $imageName);
    }
    return response()->json('Image uploaded successfully');
  }
}

Last updated

Was this helpful?