記一次laravel中使用jquery ajax上傳FormData資料時報錯解決經歷

carol2014發表於2024-04-16

很久沒寫上傳檔案的功能,偶然在laravel中用jquery ajax傳送FormData物件居然報錯了,記錄下解決方法。

路由

<?php

Route::get('test/fileUpload', [TestController::class, 'fileUpload']);
Route::post('test/getUpload', [TestController::class, 'getUpload']);

TestController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
  public function FileUpload()
  {
    return view('test.fileUpload');
  }

  public function getUpload(Request $request)
  {
    $files = $request->file('image');
    $paths = [];
    foreach ($files as $file) {
      // $file->storeAs('images',filename)
      $paths[] = $file->store('images');
    }
    dd($request->get('aa'), $request->get('bb'), $paths);
  }
}

fileUpload.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Document</title>
    <script src="{{ asset('js/jquery-1.9.1.js') }}"></script>
</head>

<body>
    <input type="file" accept="image/*" multiple="true" onchange="uploadFile(this)">
    <script>
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        function uploadFile(this_obj) {
            console.log(this_obj.files)
            const filelist = this_obj.files;
            const formData = new FormData();
            formData.append('aa', 1);
            for (let i in filelist) {
                formData.append('image[]', filelist[i]);
            }
            formData.append('bb', 2);

            console.log(formData, formData.get("aa"));
            $.ajax({
                type: "post",
                url: "getUpload",
                data: formData,
                dataType: 'json',
                success: function(res) {
                    console.log(res)
                },
                error: function(error) {}
            })
       }
    </script>
</body>

</html>

js程式碼出錯:不合法的呼叫,ajax請求甚至未傳送

記一次laravel中使用jquery ajax上傳FormData資料時報錯解決經歷

參考下之前寫的ajax傳送formData程式碼,發現少了2個配置,加上後即可正常執行。

<script>
     ...
     $.ajax({
        type: "post",
        url: "getUpload",
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        success: function(res) {
            console.log(res)
        },
        error: function(error) {}
    })
     ...

</script>

使用fetch則簡單的多:

<script>
    ...
    fetch('getUpload', {
        method: 'post',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: formData
        })
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.log(error);
        });
    ...
</script>

相關文章