多图上传有两种做法:一次请求传多张(进度是整体),或每张一个请求(每张独立进度,可并发)。这篇两种都给,并解决「部分失败」「顺序错乱」「并发过高」三个常见问题。
一、两种方案对比
| 方案 | 进度粒度 | 失败处理 | 适用 |
|---|---|---|---|
| 一次请求多文件 | 整体 | 整批重传 | 少量图片 |
| 每文件一个请求 | 单张 | 单张重试 | 相册、批量上传 |
二、方案 A:一次请求多文件
前端
<input type="file" id="files" multiple accept="image/*">
<div class="bar"><span id="bar"></span></div>
<div id="tip">0%</div>
<button id="btn">上传</button>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
$('#btn').on('click', function () {
const files = $('#files')[0].files;
if (!files.length) return alert('请选择图片');
const fd = new FormData();
for (let i = 0; i < files.length; i++) {
fd.append('images[]', files[i]);
}
$.ajax({
url: 'upload-multi.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
dataType: 'json',
xhr: function () {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
const p = Math.round(e.loaded / e.total * 100);
$('#bar').css('width', p + '%');
$('#tip').text('总进度:' + p + '%');
}
});
return xhr;
},
success: function (res) {
console.log(res);
}
});
});
</script>
服务端
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
$files = $_FILES['images'] ?? null;
if (!$files || !is_array($files['name'])) {
echo json_encode(['code' => 1, 'msg' => '没有文件'], JSON_UNESCAPED_UNICODE);
exit;
}
$allow = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp'];
$dir = __DIR__ . '/uploads/';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$ok = [];
$fail = [];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$count = count($files['name']);
for ($i = 0; $i < $count; $i++) {
$name = $files['name'][$i];
if ($files['error'][$i] !== UPLOAD_ERR_OK) {
$fail[] = ['name' => $name, 'msg' => '上传错误码 ' . $files['error'][$i]];
continue;
}
if ($files['size'][$i] > 5 * 1024 * 1024) {
$fail[] = ['name' => $name, 'msg' => '超过 5MB'];
continue;
}
$mime = $finfo->file($files['tmp_name'][$i]);
if (!isset($allow[$mime])) {
$fail[] = ['name' => $name, 'msg' => '类型不支持'];
continue;
}
$newName = date('YmdHis') . '_' . bin2hex(random_bytes(5)) . '.' . $allow[$mime];
if (move_uploaded_file($files['tmp_name'][$i], $dir . $newName)) {
$ok[] = ['name' => $newName, 'url' => '/uploads/' . $newName, 'origin' => $name];
} else {
$fail[] = ['name' => $name, 'msg' => '保存失败'];
}
}
echo json_encode([
'code' => 0,
'msg' => '完成',
'data' => ['success' => $ok, 'failed' => $fail],
], JSON_UNESCAPED_UNICODE);
三、方案 B:每张一个请求(推荐)
每张图片独立上传,进度精确到单张,失败可单独重试。
<input type="file" id="files" multiple accept="image/*">
<div id="list"></div>
<script>
const MAX_CONCURRENT = 3; // 同时最多传 3 张
let queue = [];
let running = 0;
$('#files').on('change', function () {
queue = Array.from(this.files);
queue.forEach((f, i) => {
$('#list').append(`
<div class="item" id="item-${i}">
<span class="name">${f.name}</span>
<div class="bar"><span id="bar-${i}"></span></div>
<span class="status" id="status-${i}">等待中</span>
</div>`);
});
next();
});
function next() {
while (running < MAX_CONCURRENT && queue.length) {
const file = queue.shift();
const index = $('#list .item').index($('#item-' + file.index));
upload(file);
}
}
上面这段只是骨架,完整版用下面的类来管理并发与重试。
class Uploader {
constructor(selector, options = {}) {
this.$list = $(selector);
this.max = options.max || 3;
this.taskId = 0;
this.queue = [];
this.running = 0;
}
add(files) {
Array.from(files).forEach((file) => {
const id = ++this.taskId;
this.render(id, file);
this.queue.push({ id, file });
});
this.next();
}
render(id, file) {
this.$list.append(`
<div class="item" data-id="${id}">
<span class="name">${file.name}</span>
<div class="bar"><span class="fill"></span></div>
<span class="status">等待中</span>
</div>`);
}
next() {
while (this.running < this.max && this.queue.length) {
const task = this.queue.shift();
this.running++;
this.upload(task).finally(() => {
this.running--;
this.next();
});
}
}
upload({ id, file }) {
const $item = this.$list.find(`[data-id="${id}"]`);
const $fill = $item.find('.fill');
const $status = $item.find('.status');
return new Promise((resolve) => {
const fd = new FormData();
fd.append('image', file);
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
dataType: 'json',
xhr: () => {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const p = Math.round(e.loaded / e.total * 100);
$fill.css('width', p + '%');
$status.text('上传中 ' + p + '%');
}
});
return xhr;
},
success: (res) => {
if (res.code === 0) {
$status.text('成功').addClass('ok');
$item.attr('data-url', res.data.url);
} else {
$status.text('失败:' + res.msg).addClass('err');
}
},
error: () => {
$status.text('网络错误,可重试').addClass('err');
},
complete: () => resolve()
});
});
}
}
const uploader = new Uploader('#list', { max: 3 });
$('#files').on('change', function () {
uploader.add(this.files);
});
四、并发控制为什么重要
| 并发数 | 现象 |
|---|---|
| 1 | 慢,但稳定 |
| 3~5 | 推荐,兼顾速度与稳定 |
| 20+ | 浏览器连接数打满,其他请求被阻塞 |
浏览器同域名并发通常 6 个左右,设置 3~5 最合适;同时上传太多还会拖慢页面其他请求。
五、常见问题
| 问题 | 原因 | 解决 |
|---|---|---|
| 只传上去一张 | name 没用 images[] | 表单名加 [] |
| 顺序错乱 | 并发完成顺序不同 | 用 id 绑定 DOM,不依赖顺序 |
| 部分失败 | 某张类型/大小不符 | 服务端逐张返回失败原因 |
| 内存暴涨 | 一次选几十张大图 | 限制数量 + 前端压缩 |
| 上传到一半取消 | abort | 保存 xhr 对象,调用 xhr.abort() |
六、总结
多图上传推荐「每张一个请求 + 并发上限 3~5」:进度精确、失败可重试、顺序不影响。一次请求多文件实现简单,但整体进度和整批失败会让体验变差。