Laravel + htmljs 图片上传实现
前端代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>多图片上传(最多5张)</title>
<style>
.image-preview {
display: flex;
flex-wrap: wrap;
margin-top: 20px;
}
.image-preview img {
max-width: 100px;
max-height: 100px;
margin: 5px;
border: 1px solid #ccc;
border-radius: 5px;
}
.upload-button {
margin-top: 20px;
padding: 10px 20px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.upload-button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
</style>
</head>
<body>
<h1>多图片上传(最多5张)</h1>
<input type="file" id="fileInput" multiple accept="image/*">
<button class="upload-button" id="uploadButton" disabled>上传图片</button>
<div class="image-preview" id="imagePreview"></div>
<script>
const fileInput = document.getElementById('fileInput');
const uploadButton = document.getElementById('uploadButton');
const imagePreview = document.getElementById('imagePreview');
let selectedFiles = [];
// 监听文件选择事件
fileInput.addEventListener('change', function(event) {
const files = event.target.files;
// 如果选择了超过 5 张图片,只保留前 5 张
if (files.length > 5) {
selectedFiles = Array.from(files).slice(0, 5); // 只取前 5 张
} else {
selectedFiles = Array.from(files); // 全部选中
}
imagePreview.innerHTML = ''; // 清空之前的预览
if (selectedFiles.length > 0) {
uploadButton.disabled = false; // 启用上传按钮
} else {
uploadButton.disabled = true; // 禁用上传按钮
}
// 预览选中的图片
selectedFiles.forEach(file => {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
imagePreview.appendChild(img);
};
reader.readAsDataURL(file);
});
});
// 监听上传按钮点击事件
uploadButton.addEventListener('click', function() {
if (selectedFiles.length === 0) {
alert('请先选择图片!');
return;
}
const formData = new FormData();
selectedFiles.forEach((file, index) => {
formData.append('images', file); // 将文件添加到 FormData 对象
});
// 模拟上传到服务器(替换为实际的 API 地址)
fetch('https://example.com/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert('上传成功!');
console.log('服务器返回的数据:', data);
})
.catch(error => {
console.error('上传失败:', error);
alert('上传失败,请重试!');
});
});
</script>
</body>
</html>
Laravel 后端代码
public function upload(Request $request)
{
// 检查请求方法是否为 POST
if (!$request->isMethod('post')) {
return response()->json([
'code' => 400,
'msg' => '非法请求',
], 400);
}
// 获取上传的文件
$files = $request->file('images');
// 检查是否有文件上传
if (empty($files)) {
return response()->json([
'code' => 400,
'msg' => '未上传任何文件',
], 400);
}
// 如果上传的是单个文件,转换为数组形式统一处理
if (!is_array($files)) {
$files = [$files];
}
// 定义存储路径
$uploadPaths = [];
// 遍历文件并保存
foreach ($files as $file) {
// 验证文件是否有效
if (!$file->isValid()) {
continue; // 跳过无效文件
}
// 保存文件到指定目录(按日期分类)
$path = Storage::disk('public')->putFile(date('Ymd'), $file); // 保存到 uploads 磁盘的日期目录下
if ($path) {
$uploadPaths[] = $path; // 记录保存路径
}
}
// 检查是否有文件成功保存
if (empty($uploadPaths)) {
return response()->json([
'code' => 400,
'msg' => '文件上传失败,请检查文件格式或大小',
], 400);
}
// 返回成功响应
return response()->json([
'code' => 0,
'msg' => '上传成功',
'data' => $uploadPaths,
]);
}