ThinkPHP 是一个流行的 PHP 开发框架,提供了丰富的功能和组件,方便开发者快速构建 Web 应用程序。图片批量上传是指在一次请求中上传多张图片的功能,这在许多应用场景中非常有用,比如用户上传多张照片到社交平台或电商网站。
使用 HTML 和 JavaScript 实现批量上传功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>批量上传图片</title>
</head>
<body>
<input type="file" id="fileInput" multiple>
<button id="uploadButton">上传</button>
<script>
document.getElementById('uploadButton').addEventListener('click', function() {
const files = document.getElementById('fileInput').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append('files[]', files[i]);
}
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
使用 ThinkPHP 实现图片批量上传:
<?php
namespace app\controller;
use think\Controller;
use think\Request;
class UploadController extends Controller
{
public function index(Request $request)
{
if ($request->isPost()) {
$files = $request->file('files');
$savePath = './uploads/';
$info = [];
foreach ($files as $file) {
if ($file->isValid()) {
$info[] = $file->move($savePath);
}
}
if ($info) {
return json(['code' => 0, 'msg' => '上传成功', 'data' => $info]);
} else {
return json(['code' => 1, 'msg' => '上传失败']);
}
} else {
return view();
}
}
}
php.ini
文件中的 upload_max_filesize
和 post_max_size
来解决。php.ini
文件中的 upload_max_filesize
和 post_max_size
来解决。通过以上步骤和解决方法,你可以实现一个基本的图片批量上传功能。根据具体需求,还可以进一步优化和扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云