php上传多张带预览图的图片并且支持跨域上传 前端后端代码
时间: 2024-10-19 22:08:25 浏览: 19
在 PHP 中,处理多张图片上传以及生成预览图,并考虑到跨域问题,你需要做以下几个步骤:
前端(HTML + JavaScript + AJAX):
```html
<!-- 使用HTML5的FormData -->
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" multiple name="images[]" accept="image/*" onchange="previewFiles()">
<div id="preview"></div>
<button type="submit">Upload</button>
</form>
<script>
function previewFiles() {
// 预览文件
const input = document.querySelector('#images');
const previewContainer = document.getElementById('preview');
input.files.forEach(file => {
const reader = new FileReader();
reader.onload = (event) => {
previewContainer.innerHTML += `<img src="${event.target.result}" alt="${file.name}">`;
};
reader.readAsDataURL(file);
});
}
// 跨域上传AJAX
$.ajax({
url: 'upload.php',
type: 'POST',
data: new FormData(document.getElementById('uploadForm')),
processData: false,
contentType: false,
xhr: function() { return new XMLHttpRequest(); },
xhrFields: {
withCredentials: true, // 如果服务器需要的话,设置跨域发送Cookie
},
success: function(data) {
console.log(data);
}
});
</script>
```
后端(PHP - 使用 Laravel 或者原生 PHP 示例):
```php
// upload.php (Laravel)
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
public function store(Request $request)
{
$files = $request->file('images');
foreach ($files as $file) {
// 文件名保存和存储
$filename = time() . '-' . $file->getClientOriginalName();
$file->move(public_path('uploads'), $filename);
// 图片处理并生成缩略图
$image = Image::make(public_path('/uploads/' . $filename));
$thumbnailPath = public_path('/uploads/thumbnails/' . $filename);
$image->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
})->save($thumbnailPath);
}
// 返回响应,例如JSON
return response()->json(['status' => 'success', 'message' => 'Images uploaded successfully']);
}
// 或者原生 PHP 示例
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$dir = 'uploads/';
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
$file_info = pathinfo($_FILES['images']['name'][$key]);
$new_file_name = $file_info['basename'];
move_uploaded_file($tmp_name, $dir . '/' . $new_file_name);
// 缩略图处理
list($width, $height) = getimagesize($dir . '/' . $new_file_name);
imagecreatetruecolor(300, min(300, $height / $width * $width)); // 创建新的图像资源
$source = imagecreatefromjpeg($dir . '/' . $new_file_name); // 加载原始图片
imagecopyresampled($dest, $source, 0, 0, 0, 0, 300, min(300, $height), $width, $height); // 缩放并保存到新位置
imagejpeg($dest, $dir . '/thumbnails/' . $new_file_name);
}
// 返回响应,例如JSON
echo json_encode(['status' => 'success', 'message' => 'Images uploaded successfully']);
}
```
阅读全文