编程语言
12828
很久没写上传文件的功能,偶然在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请求甚至未发送
参考下之前写的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>