图片上传要显示进度条,关键在 xhr.upload.onprogress:jQuery 的 $.ajax 默认不支持,需要自己返回并监听 xhr 对象。这篇用 PHP 8 + 原生 jQuery 实现单图上传、实时进度、前端预览与服务端校验,代码可直接运行。参考:jQuery.ajax。
一、效果与思路
- 选择图片后立即本地预览;
- 点击上传,进度条从 0% 走到 100%;
- 上传完成显示服务端返回的图片地址;
- 服务端校验类型、大小、真实 MIME,重命名保存。
upload-single/
├── index.html # 前端页面
├── upload.php # 上传接口
└── uploads/ # 保存目录(需可写)
二、前端页面
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>单图上传</title>
<style>
.box { width: 420px; margin: 40px auto; font-family: sans-serif; }
.preview { width: 200px; height: 200px; border: 1px dashed #ccc; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #999; overflow: hidden; }
.preview img { width: 100%; height: 100%; object-fit: cover; }
.bar { height: 10px; background: #eee; border-radius: 5px; margin: 12px 0; overflow: hidden; }
.bar span { display: block; height: 100%; width: 0; background: #3157d5; transition: width .15s; }
.tip { font-size: 13px; color: #666; }
</style>
</head>
<body>
<div class="box">
<div class="preview" id="preview">未选择图片</div>
<input type="file" id="file" accept="image/*">
<div class="bar"><span id="bar"></span></div>
<div class="tip" id="tip">0%</div>
<button id="btn">开始上传</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
$(function () {
let file = null;
// 1. 选择后本地预览
$('#file').on('change', function () {
const f = this.files[0];
if (!f) return;
if (!f.type.startsWith('image/')) {
alert('请选择图片');
return;
}
if (f.size > 5 * 1024 * 1024) {
alert('图片不能超过 5MB');
return;
}
file = f;
const url = URL.createObjectURL(f);
$('#preview').html('<img src="' + url + '">');
$('#tip').text('已选择:' + f.name + '(' + (f.size / 1024).toFixed(1) + ' KB)');
});
// 2. 上传
$('#btn').on('click', function () {
if (!file) {
alert('请先选择图片');
return;
}
const fd = new FormData();
fd.append('image', file);
const $btn = $(this).prop('disabled', true).text('上传中...');
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
processData: false, // 必须
contentType: false, // 必须
dataType: 'json',
xhr: function () {
const xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
const percent = Math.round(e.loaded / e.total * 100);
$('#bar').css('width', percent + '%');
$('#tip').text('上传中:' + percent + '%');
}
}, false);
return xhr;
},
success: function (res) {
if (res.code === 0) {
$('#tip').text('上传成功:' + res.data.url);
$('#bar').css('width', '100%');
} else {
$('#tip').text('失败:' + res.msg);
}
},
error: function () {
$('#tip').text('网络错误,请重试');
},
complete: function () {
$btn.prop('disabled', false).text('开始上传');
}
});
});
});
</script>
</body>
</html>
三、PHP 上传接口
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
function jsonOut(int $code, string $msg, array $data = []): void
{
echo json_encode(['code' => $code, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
exit;
}
// 1. 基础检查
if (!isset($_FILES['image'])) {
jsonOut(1, '没有收到文件');
}
$file = $_FILES['image'];
if ($file['error'] !== UPLOAD_ERR_OK) {
$map = [
UPLOAD_ERR_INI_SIZE => '超过 php.ini 限制',
UPLOAD_ERR_FORM_SIZE => '超过表单限制',
UPLOAD_ERR_PARTIAL = '只上传了一部分',
UPLOAD_ERR_NO_FILE = '没有文件',
UPLOAD_ERR_NO_TMP_DIR = '缺少临时目录',
UPLOAD_ERR_CANT_WRITE = '写入失败',
];
jsonOut(1, $map[$file['error']] ?? '上传失败');
}
// 2. 大小限制 5MB
if ($file['size'] > 5 * 1024 * 1024) {
jsonOut(1, '图片不能超过 5MB');
}
// 3. 真实 MIME 校验(不能只看扩展名)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
$allow = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
];
if (!isset($allow[$mime])) {
jsonOut(1, '只支持 jpg/png/gif/webp');
}
// 4. 生成安全文件名
$ext = $allow[$mime];
$name = date('YmdHis') . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
$dir = __DIR__ . '/uploads/';
if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
jsonOut(1, '创建目录失败');
}
// 5. 移动文件
$target = $dir . $name;
if (!move_uploaded_file($file['tmp_name'], $target)) {
jsonOut(1, '保存失败');
}
// 6. 返回访问地址
jsonOut(0, '上传成功', [
'url' => '/uploads/' . $name,
'name' => $name,
'size' => $file['size'],
'mime' => $mime,
]);
四、进度条原理
| 事件 | 触发时机 |
|---|---|
xhr.upload.onprogress | 上传过程中持续触发 |
e.loaded / e.total | 已上传字节 / 总字节 |
e.lengthComputable | 总大小是否已知 |
success | 服务端返回后 |
注意:progress 只反映「浏览器到服务器」的传输进度,服务端处理(校验、压缩)期间进度会停在 100% 等待响应。
五、安全要点
| 风险 | 防护 |
|---|---|
| 上传 php/jsp 脚本 | 白名单扩展名 + 真实 MIME |
| 文件名注入 | 重命名为随机串 |
| 目录穿越 | 不拼接用户输入 |
| 图片马 | 二次渲染或剥离元数据 |
| 超大文件 | 前端 + 后端双重限制 |
| 目录执行权限 | uploads 目录禁止执行 PHP |
六、常见问题
| 现象 | 原因 | 解决 |
|---|---|---|
| 进度不动 | 没设 xhr 或用了 contentType | 按文中配置 |
| $_FILES 为空 | 超过 upload_max_filesize | 调 php.ini |
| 上传成功但 404 | 路径不对 | 检查 uploads 目录 |
| 中文名乱码 | 文件名编码 | 重命名即可 |
| 大图上传失败 | Nginx client_max_body_size | 调大到 10m |
七、总结
单图上传就三件事:FormData 组装、processData/contentType 设为 false、监听 xhr.upload.onprogress。服务端记得用 finfo 校验真实类型,并把文件名改成随机串。