php plupload.Uploader ajax 上传图片前后台代码
时间: 2024-10-29 21:12:33 浏览: 29
PHP Plupload Uploader 是一个强大的前端文件上传组件,常用于 AJAX 上载大文件,包括图片。以下是基本的前后端代码示例:
**前端(HTML + JavaScript with Plupload):**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="plupload/plupload.full.min.js"></script>
<script src="plupload/jquery.plupload.queue.js"></script>
</head>
<body>
<div id="container">
<!-- 插件会在这里显示上传进度等信息 -->
<div id="uploader"></div>
</div>
<script>
$(document).ready(function() {
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,browserplus',
url: 'php/upload.php', // 后端处理文件上传的PHP脚本地址
browse_button: 'selectFiles', // 文件选择按钮ID
max_file_size: '10mb',
filters: {
mime_types: [
{ title: "Image files", extensions: "jpg,jpeg,png,gif" }
]
},
init: {
FilesAdded: function(up, files) {
up.start();
},
UploadProgress: function(up, file) {
$('#progress').width(file.percent + '%');
},
FileUploaded: function(up, file, info) {
console.log('File uploaded successfully:', file.name);
}
}
});
uploader.init();
});
</script>
</body>
</html>
```
**后端(PHP - upload.php):**
```php
<?php
// 初始化 PHP 处理
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
// 检查目录是否存在并有写入权限
if (!is_dir($uploaddir)) {
mkdir($uploaddir, 0777, true);
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "文件 '" . htmlspecialchars($_FILES['file']['name']) . "' 上传成功.";
} else {
echo "上传失败: " . htmlspecialchars($_FILES['file']['error']);
}
?>
```
上述代码中,前端使用 Plupload 进行图片上传,用户选择图片后,通过AJAX发送到后端的`upload.php`。后端接收请求,保存上传的图片。
阅读全文