如何在 Laravel 8 中使用 jQuery AJAX 和顯示預覽上傳文件

使用 AJAX,您可以將文件上傳到服務器而無需重新加載頁面。

需要通過 AJAX 請求發送 CSRF 令牌以上傳文件。

在本教程中,我將展示如何使用 jQuery AJAX 上傳文件並在 Laravel 8 中顯示預覽。

1.控制器

創建一個PageController控制器。

php artisan make:controller PageController

創建 2 個方法 –

  • index() -加載index視圖。
  • uploadFile() -此方法用於上傳文件。

創建$data數組來存儲返迴響應。

定義文件驗證。我將最大文件大小設置為 2 MB (2048 Kb)。

如果文件未經過驗證,則分配0$data['success']並驗證響應到$data['error'].

如果文件被驗證,則將文件名$filename和文件擴展名分配給$extension變量。將上傳位置分配"files"$location變量。

執行 $file->move($location,$filename); 以存儲文件。

分配1$data['success'],'Uploaded Successfully!'$data['message'], 文件路徑$data['filepath']和文件擴展名給$data['extension'].

如果文件未上傳,則分配 2$data['success']並將'File not uploaded.'消息發送給$data['message']

以 JSON 格式返回$data數組。

完成的代碼

<?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 = 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);

             // 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);
   }

}

2. 路線

  • 打開routes/web.php文件。
  • 定義 2 條路線 –
    • / -加載索引視圖。
    • /uploadFile -這用於使用 AJAX 上傳文件。

完成的代碼

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PageController;

Route::get('/', [PageController::class, 'index']);
Route::post('/uploadFile', [PageController::class, 'uploadFile'])->name('uploadFile');

3.查看

在. index.blade.php_resources/views/

<meta > 存儲在標籤中的 CSRF 令牌。

<div id="responseMsg">使用 jQuery顯示文件上傳響應消息。

使用 jQuery創建 <img > 並 添加<a > 元素 <div id="filepreview"> 以根據文件擴展名顯示文件預覽。

創建一個文件元素和一個按鈕。<div id="err_file">如果文件未使用 jQuery 驗證,則顯示錯誤。

腳本

從標籤中讀取 CSRF 令牌<meta >並分配給CSRF_TOKEN變量。

在按鈕上單擊讀取所選文件並分配給files變量。

如果未選擇alert("Please select a file.");文件,則使用 FormData 對像傳遞選定的文件。CSRF_TOKEN此外,使用 FormData傳遞。

將 AJAX POST 請求發送到 "{{route('uploadFile')}} 將 FormData 對像作為數據傳遞​​的位置。

回調成功後檢查上傳狀態。

如果 response.success == 1 表示文件成功上傳。顯示響應消息並根據文件擴展名預覽文件。

如果 response.success == 2 表示文件未上傳。顯示響應消息。

如果 response.success 不等於 1 或 2,則表示文件未經過驗證。顯示錯誤信息。

完成的代碼

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

4. 輸出

查看輸出


5. 結論

如果您想在發送 AJAX 請求時傳遞額外的數據,請使用 FormData 對象,例如 – fd.append('filename',"file 1");。這裡,fd是 FormData 對象。

如果您允許上傳大文件,請務必檢查php.ini 文件中upload_max_filesize的值。post_max_size

來源:  https ://makitweb.com

#php #laravel #jquery #ajax

What is GEEK

Buddha Community

如何在 Laravel 8 中使用 jQuery AJAX 和顯示預覽上傳文件
Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

I am Developer

1593933651

Laravel 7 Ajax Dynamic Dependent Dropdown

In this tutorial i will share with you how to create dependent dropdown using ajax in laravel. Or how to create selected subcategories dropdown based on selected category dropdown using jQuery ajax in laravel apps.

As well as learn, how to retrieve data from database on onchange select category dropdown using jQuery ajax in drop down list in laravel.

Laravel Ajax Dynamic Dependent Dropdown Tutorial

Follow the below steps and implement dependent dropdown using jQuery ajax in laravel app:

  1. Step 1: Install Laravel New App
  2. Step 2: Add Database Details
  3. Step 3: Create Model and Migration
  4. Step 4: Add Routes
  5. Step 5: Create Controllers By Artisan
  6. Step 6: Create Blade Views
  7. Step 7: Run Development Server

Originally published at https://www.tutsmake.com/laravel-dynamic-dependent-dropdown-using-ajax-example

#laravel jquery ajax categories and subcategories select dropdown #jquery ajax dynamic dependent dropdown in laravel 7 #laravel dynamic dependent dropdown using ajax #display category and subcategory in laravel #onchange ajax jquery in laravel #how to make dynamic dropdown in laravel

I am Developer

1617089618

Laravel 8 Tutorial for Beginners

Hello everyone! I just updated this tutorial for Laravel 8. In this tutorial, we’ll go through the basics of the Laravel framework by building a simple blogging system. Note that this tutorial is only for beginners who are interested in web development but don’t know where to start. Check it out if you are interested: Laravel Tutorial For Beginners

Laravel is a very powerful framework that follows the MVC structure. It is designed for web developers who need a simple, elegant yet powerful toolkit to build a fully-featured website.

Recommended:-Laravel Try Catch

#laravel 8 tutorial #laravel 8 tutorial crud #laravel 8 tutorial point #laravel 8 auth tutorial #laravel 8 project example #laravel 8 tutorial for beginners

I am Developer

1599536794

Laravel 8 New Features | Release Notes - Tuts Make

In this post, i will show you what’s new in laravel 8 version.

#What’s new in Laravel 8?

  • 1 - Change Path Of Default Models Directory
  • 2 - Removed Controllers Namespace Prefix
  • 3 - Enhancements on php artisan serve
  • 4 - Enhanced Rate Limiting
  • 5 - Enhanced on Route Caching
  • 6 - Update on Pagination Design
  • 8 - Dynamic Blade Componenets
  • 7 - Update Syntax for Closure Based Event Listeners
  • 8 - Queueable Model Event Listeners
  • 9 - Maintenance mode: secret access
  • 10 - Maintenance mode: pre-rendered page
  • 11 - Queued job batching
  • 12 - Queue backoff()
  • 13 - Laravel Factory

https://www.tutsmake.com/laravel-8-new-features-release-notes/

#laravel 8 features #laravel 8 release date #laravel 8 tutorial #news - laravel 8 new features #what's new in laravel 8 #laravel 8 release notes

I am Developer

1597469369

Crop and Resize Image Before Upload In Laravel Using with jQuery Copper JS

Crop and resize image size before upload in laravel using jquery copper js. In this post, i will show you how to crop and resize image size in laravel using jQuery copper js in laravel.

This laravel crop image before upload using cropper js looks like:

laravel crop image before upload

Laravel Crop Image Before Uploading using Cropper js Tutorial

Laravel crop image before upload tutorial, follow the following steps and learn how to use cropper js to crop image before uploading in laravel app:

  • Step 1: Install New Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Migration & Model
  • Step 4: Add Route
  • Step 5: Create Controller By Artisan
  • Step 6: Create Blade View
  • Step 7: Make Upload Directory
  • Step 8: Start Development Server

Read More => https://www.tutsmake.com/laravel-crop-image-before-upload-using-jquery-copper-js/

Live Demo Laravel Crop image Before Upload.

#laravel crop image before upload, #laravel crop and resize image using cropper.js #ajax image upload and crop with jquery and laravel #crop and upload image ajax jquery laravel #crop image while uploading with jquery laravel #image crop and upload using jquery with laravel ajax