---
description: https://makitweb.com/how-to-upload-a-file-using-jquery-ajax-in-laravel-8/
---

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

Không dùng Database, không dùng form :joy:

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FAsgbCCGSs8zVIBjseHYN%2Fimage.png?alt=media&#x26;token=20aed2a5-17c8-40d5-9628-729721c153bc" 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%2FRPMyKYbVD20hh79TtCEd%2Fimage.png?alt=media&#x26;token=aceb78c1-e568-4b08-ba5e-f51c8d96bd29" alt=""><figcaption></figcaption></figure>

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

```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\app\Http\Controllers\PageController.php

```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)
  {
    $data = [];
    $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);
        // 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);
  }
}

```

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

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

```

### Hoặc  thay đổi&#x20;

```
<input type="button" id="submit" value='Submit' class='btn btn-success'> 
thành 
<div id="submit" class='btn btn-success'>Submit</div>
```

```blade
<!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">
            <div id="submit" class='btn btn-success'>Submit</div>
          </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>

```
