跳到正文
控制台

在浏览器中上传与下载

浏览器里不要使用 AccessKey,任何人都能从网页代码里看到它。正确做法是:服务端签发预签名 URL,浏览器拿着 URL 直接和 S4 传输,文件不经过你的服务器。

准备工作

准备桶与密钥

创建存储桶 和 子账户,给子账户授权上传目录(例如 uploads/)的读、写权限。密钥只放在服务端。

检查跨域设置

桶没有任何跨域规则时,默认允许所有来源。已经配置过规则的桶,需要允许你的网站使用 PUT,并在 暴露 Headers 里填写 ETag(分片上传必需),见 跨域设置。

安装服务端依赖

npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

服务端

下面是一个完整的 Node.js 服务,提供单次上传和分片上传需要的接口。其他语言用对应 SDK 的预签名方法实现同样的接口即可。

server.mjs
import http from "node:http";
import {
  S3Client, PutObjectCommand, CreateMultipartUploadCommand, UploadPartCommand,
  CompleteMultipartUploadCommand, AbortMultipartUploadCommand,
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const Bucket = "my-bucket";
const s3 = new S3Client({
  endpoint: "https://s3.bitiful.net",
  region: "cn-east-1",
  credentials: {
    accessKeyId: process.env.S4_ACCESS_KEY,
    secretAccessKey: process.env.S4_SECRET_KEY,
  },
  // 预签名上传时不把校验和写进 URL
  requestChecksumCalculation: "WHEN_REQUIRED",
});

const MAX_SIZE = 5 * 1024 ** 3; // 允许的最大文件:5 GiB
const PART_SIZE = 16 * 1024 ** 2; // 每片 16 MiB
const sign = (cmd) => getSignedUrl(s3, cmd, { expiresIn: 3600 });

// 对象键由服务端决定,不要直接使用客户端传来的路径
function newKey(userId, filename) {
  const ext = /\.[a-z0-9]{1,8}$/i.exec(filename)?.[0].toLowerCase() ?? "";
  return `uploads/${userId}/${crypto.randomUUID()}${ext}`;
}

// 分片接口收到的 key 必须属于当前用户
function checkKey(userId, key) {
  if (!key.startsWith(`uploads/${userId}/`)) throw new Error("无权操作");
}

const routes = {
  // 单次上传:返回一个 PUT 链接
  async "/upload/single"(userId, { filename, size }) {
    if (!(size > 0 && size <= MAX_SIZE)) throw new Error("文件大小不合法");
    const Key = newKey(userId, filename);
    // ContentLength 会参与签名,实际上传的大小必须一致
    const url = await getSignedUrl(
      s3,
      new PutObjectCommand({ Bucket, Key, ContentLength: size }),
      { expiresIn: 600 },
    );
    return { key: Key, url };
  },

  // 分片上传:创建任务,返回每一片的 PUT 链接
  async "/upload/multipart/create"(userId, { filename, size, type }) {
    if (!(size > 0 && size <= MAX_SIZE)) throw new Error("文件大小不合法");
    const Key = newKey(userId, filename);
    const { UploadId } = await s3.send(
      new CreateMultipartUploadCommand({ Bucket, Key, ContentType: type || undefined }),
    );
    const count = Math.ceil(size / PART_SIZE);
    const urls = await Promise.all(
      Array.from({ length: count }, (_, i) =>
        sign(new UploadPartCommand({ Bucket, Key, UploadId, PartNumber: i + 1 })),
      ),
    );
    return { key: Key, uploadId: UploadId, partSize: PART_SIZE, urls };
  },

  // 合并分片
  async "/upload/multipart/complete"(userId, { key, uploadId, parts }) {
    checkKey(userId, key);
    await s3.send(new CompleteMultipartUploadCommand({
      Bucket,
      Key: key,
      UploadId: uploadId,
      MultipartUpload: {
        Parts: parts
          .toSorted((a, b) => a.partNumber - b.partNumber)
          .map((p) => ({ PartNumber: p.partNumber, ETag: p.etag })),
      },
    }));
    return { key };
  },

  // 放弃上传,清理已上传的分片
  async "/upload/multipart/abort"(userId, { key, uploadId }) {
    checkKey(userId, key);
    await s3.send(new AbortMultipartUploadCommand({ Bucket, Key: key, UploadId: uploadId }));
    return {};
  },
};

http.createServer(async (req, res) => {
  const route = req.method === "POST" && routes[req.url];
  if (!route) return res.writeHead(404).end();
  try {
    const userId = "demo"; // 换成你的登录校验
    let body = "";
    for await (const chunk of req) body += chunk;
    const data = await route(userId, JSON.parse(body));
    res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(data));
  } catch (err) {
    console.error(err);
    res.writeHead(400, { "Content-Type": "application/json" })
      .end(JSON.stringify({ message: "上传请求失败" }));
  }
}).listen(3000);

安全要点:

  • 对象键由服务端生成,不要直接使用客户端传来的路径,防止覆盖别人的文件;
  • 接口必须校验登录状态,分片接口要校验对象键属于当前用户;
  • ContentLength 参与签名后,上传的大小必须与声明的一致,否则返回 403;
  • 还可以加上 x-bitiful-max-requests=1 防止链接被重复使用,见 预签名 URL。

上传小文件

先写一个调用服务端接口的函数:

upload.js
async function api(path, data) {
  const res = await fetch(path, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
  if (!res.ok) throw new Error(`${path} ${res.status}`);
  return res.json();
}

再上传文件,onProgress 的参数是 0 到 1 的进度:

upload.js
// fetch 拿不到上传进度,这里用 XMLHttpRequest
function put(url, body, onProgress) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("PUT", url);
    xhr.upload.onprogress = (e) => onProgress?.(e.loaded);
    xhr.onload = () =>
      xhr.status === 200
        ? resolve(xhr.getResponseHeader("ETag"))
        : reject(new Error(`${xhr.status} ${xhr.responseText}`));
    xhr.onerror = () => reject(new Error("网络错误或跨域被拦截"));
    xhr.send(body);
  });
}

async function uploadSingle(file, onProgress) {
  const { key, url } = await api("/upload/single", { filename: file.name, size: file.size });
  await put(url, file, (n) => onProgress?.(n / file.size));
  return key;
}
index.html
<input type="file" id="file" />
<progress id="bar" max="1" value="0"></progress>
<script type="module">
  import { uploadSingle } from "./upload.js"; // 在 upload.js 里导出

  document.querySelector("#file").addEventListener("change", async (e) => {
    const bar = document.querySelector("#bar");
    const key = await uploadSingle(e.target.files[0], (p) => (bar.value = p));
    console.log("上传完成", key);
  });
</script>

用 XMLHttpRequest 或 fetch 直接发送 File 时,浏览器会自动带上它识别出的 Content-Type。如果签名时没有指定 ContentType,这个头不参与签名,可以正常上传,S4 会把它保存为对象的类型。想让 S4 自动检测类型,请发送没有类型的内容,例如 file.slice(0, file.size, "")。

上传大文件

超过 100 MB 的文件建议分片:多片并发更快,单片失败只重传这一片。

upload.js
async function uploadMultipart(file, onProgress, concurrency = 4) {
  const { key, uploadId, partSize, urls } = await api("/upload/multipart/create", {
    filename: file.name,
    size: file.size,
    type: file.type,
  });

  const loaded = new Array(urls.length).fill(0);
  const parts = [];
  let next = 0;

  async function worker() {
    while (next < urls.length) {
      const i = next++;
      const blob = file.slice(i * partSize, (i + 1) * partSize);
      for (let attempt = 1; ; attempt++) {
        try {
          const etag = await put(urls[i], blob, (n) => {
            loaded[i] = n;
            onProgress?.(loaded.reduce((a, b) => a + b, 0) / file.size);
          });
          parts.push({ partNumber: i + 1, etag });
          break;
        } catch (err) {
          if (attempt === 3) throw err; // 每片最多尝试 3 次
          await new Promise((r) => setTimeout(r, attempt * 1000));
        }
      }
    }
  }

  try {
    await Promise.all(Array.from({ length: concurrency }, worker));
    await api("/upload/multipart/complete", { key, uploadId, parts });
    return key;
  } catch (err) {
    await api("/upload/multipart/abort", { key, uploadId }).catch(() => {});
    throw err;
  }
}

说明:

  • 每片 5 MiB 到 20 GiB,最后一片可以更小,最多 10000 片;
  • 合并时需要每一片的 ETag,浏览器读不到它就是跨域没有暴露 ETag;
  • 失败或用户取消时要调用 abort,没有完成的分片会一直保留并占用存储;
  • 预签名链接有有效期,超大文件请适当延长,或分批申请链接。

下载

服务端用 GetObject 生成预签名 URL 返回给前端,前端直接跳转:

download.js
async function download(key) {
  const { url } = await api("/download", { key }); // 你的接口
  location.href = url;
}

通过桶默认域名下载时,浏览器会保存文件而不是打开。要指定文件名,在签名时加 ResponseContentDisposition。需要在页面里直接显示图片、视频,请用 CDN 加速域名。

常见问题

控制台报 CORS 错误

先看网络面板里的真实状态码。403 等错误响应也可能被浏览器显示成跨域错误。确认来源、协议、端口与跨域规则一致,修改规则后用无痕窗口测试。

上传返回 403 SignatureDoesNotMatch

签名时指定了 ContentType 而上传时不一致;或文件大小与 ContentLength 不一致;或 URL 在传递过程中被转义(& 变成 &amp;)。

小程序里怎么上传

微信小程序的 wx.uploadFile 只支持 POST 表单。可以用 wx.request 以 PUT 发送 ArrayBuffer,适合小文件;域名要加入小程序后台的合法域名。

可以在浏览器里用 AWS SDK 吗

技术上可以,但需要密钥,S4 不支持 STS 临时凭证,所以请使用预签名 URL。

相关文档