# 在浏览器中上传与下载

> 浏览器直传缤纷云 S4：服务端签发预签名 URL，前端带进度上传，大文件并发分片、失败重试与取消的完整示例。

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

```mermaid
sequenceDiagram
  participant B as 浏览器
  participant A as 你的服务端
  participant S as S4
  B->>A: 申请上传（文件名、大小）
  A-->>B: 预签名 URL
  B->>S: PUT 文件
  S-->>B: 200 和 ETag
```

## 准备工作

### 准备桶与密钥

[创建存储桶](https://docs.bitiful.com/bitiful-s4/handbook/buckets.md) 和 [子账户](https://docs.bitiful.com/bitiful-s4/handbook/access-keys.md)，给子账户授权上传目录（例如 `uploads/`）的读、写权限。密钥只放在服务端。

### 检查跨域设置

桶没有任何跨域规则时，默认允许所有来源。已经配置过规则的桶，需要允许你的网站使用 `PUT`，并在 **暴露 Headers** 里填写 `ETag`（分片上传必需），见 [跨域设置](https://docs.bitiful.com/bitiful-s4/handbook/cors.md)。

### 安装服务端依赖

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

## 服务端

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

```javascript title="server.mjs" maxLines=0
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](https://docs.bitiful.com/developer/s3/presigned-url.md)。

## 上传小文件

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

```javascript title="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 的进度：

```javascript title="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;
}
```

```html title="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>
```

> **Info**
>
> 用 XMLHttpRequest 或 fetch 直接发送 `File` 时，浏览器会自动带上它识别出的 `Content-Type`。如果签名时没有指定 ContentType，这个头不参与签名，可以正常上传，S4 会把它保存为对象的类型。想让 S4 [自动检测类型](https://docs.bitiful.com/best-practice/auto-detect-mime.md)，请发送没有类型的内容，例如 `file.slice(0, file.size, "")`。

## 上传大文件

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

```javascript title="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 返回给前端，前端直接跳转：

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

通过桶默认域名下载时，浏览器会保存文件而不是打开。要指定文件名，在签名时加 `ResponseContentDisposition`。需要在页面里直接显示图片、视频，请用 [CDN 加速域名](https://docs.bitiful.com/cdn/intro.md)。

## 常见问题

<details>
<summary>控制台报 CORS 错误</summary>

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

</details>

<details>
<summary>上传返回 403 SignatureDoesNotMatch</summary>

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

</details>

<details>
<summary>小程序里怎么上传</summary>

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

</details>

<details>
<summary>可以在浏览器里用 AWS SDK 吗</summary>

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

</details>

## 相关文档

[**预签名 URL 与扩展参数**](https://docs.bitiful.com/developer/s3/presigned-url.md)

限次、限速、同步传输等参数的完整说明。

[**错误码与排查**](https://docs.bitiful.com/developer/s3/errors.md)

403、SignatureDoesNotMatch 等问题的排查清单。

[**S3 API 兼容性**](https://docs.bitiful.com/developer/s3/compatibility.md)

各操作的支持情况与差异。

[**在客户端中安全地上传文件**](https://docs.bitiful.com/best-practice/web-uploads.md)

浏览器与 App 直传的推荐做法。
