jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。Laravel 是一个基于 PHP 的全栈框架,提供了强大的工具来创建现代 Web 应用程序。
假设你有一个网页,用户可以在上面上传图片,然后这些图片需要被发送到 Laravel 后端进行存储和处理。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<button type="submit">Upload</button>
</form>
<script>
$(document).ready(function() {
$('#uploadForm').on('submit', function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
});
});
</script>
</body>
</html>
routes/web.php
):Route::post('/upload', [ImageController::class, 'upload']);
app/Http/Controllers/ImageController.php
):<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class ImageController extends Controller
{
public function upload(Request $request)
{
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Storage::disk('public')->put($filename, file_get_contents($image));
return response()->json(['message' => 'Image uploaded successfully', 'filename' => $filename]);
} else {
return response()->json(['error' => 'No image found'], 400);
}
}
}
config/filesystems.php
):'disks' => [
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
],
php.ini
文件来解决。php.ini
文件来解决。storage
目录有写权限。storage
目录有写权限。通过以上步骤,你可以使用 jQuery 获取图像并将其发送到 Laravel 后端进行处理和存储。
领取专属 10元无门槛券
手把手带您无忧上云