# Upload and download in the browser

> Upload directly from the browser to Bitiful S4: the server issues presigned URLs and the frontend uploads with progress, with complete examples of concurrent multipart uploads for large files, retries, and cancellation.

Never use an AccessKey in the browser; anyone can see it in the page code. The correct approach is for your server to issue presigned URLs, and the browser then transfers files directly with S4 using those URLs, so files never pass through your server.

```mermaid
sequenceDiagram
  participant B as Browser
  participant A as Your server
  participant S as S4
  B->>A: Request upload (file name, size)
  A-->>B: Presigned URL
  B->>S: PUT file
  S-->>B: 200 and ETag
```

## Prerequisites

### Prepare the bucket and keys

[Create a bucket](https://docs.bitiful.com/en/bitiful-s4/handbook/buckets.md) and a [sub-user](https://docs.bitiful.com/en/bitiful-s4/handbook/access-keys.md), and grant the sub-user read and write permissions on the upload directory (for example `uploads/`). Keep the keys on the server only.

### Check the CORS settings

If a bucket has no CORS rules, all origins are allowed by default. For a bucket that already has rules configured, allow `PUT` for your website, and enter `ETag` under **Exposed Headers (暴露 Headers)** (required for multipart uploads). See [CORS settings](https://docs.bitiful.com/en/bitiful-s4/handbook/cors.md).

### Install server dependencies

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

## Server

Below is a complete Node.js server that provides the endpoints needed for single and multipart uploads. In other languages, implement the same endpoints with the corresponding SDK's presign methods.

```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,
  },
  // Do not put the checksum in the URL for presigned uploads
  requestChecksumCalculation: "WHEN_REQUIRED",
});

const MAX_SIZE = 5 * 1024 ** 3; // Maximum allowed file size: 5 GiB
const PART_SIZE = 16 * 1024 ** 2; // 16 MiB per part
const sign = (cmd) => getSignedUrl(s3, cmd, { expiresIn: 3600 });

// The server decides the object key; do not use the path sent by the client directly
function newKey(userId, filename) {
  const ext = /\.[a-z0-9]{1,8}$/i.exec(filename)?.[0].toLowerCase() ?? "";
  return `uploads/${userId}/${crypto.randomUUID()}${ext}`;
}

// The key received by the multipart endpoints must belong to the current user
function checkKey(userId, key) {
  if (!key.startsWith(`uploads/${userId}/`)) throw new Error("Not authorized");
}

const routes = {
  // Single upload: return one PUT URL
  async "/upload/single"(userId, { filename, size }) {
    if (!(size > 0 && size <= MAX_SIZE)) throw new Error("Invalid file size");
    const Key = newKey(userId, filename);
    // ContentLength is included in the signature; the actual upload size must match
    const url = await getSignedUrl(
      s3,
      new PutObjectCommand({ Bucket, Key, ContentLength: size }),
      { expiresIn: 600 },
    );
    return { key: Key, url };
  },

  // Multipart upload: create the task and return a PUT URL for each part
  async "/upload/multipart/create"(userId, { filename, size, type }) {
    if (!(size > 0 && size <= MAX_SIZE)) throw new Error("Invalid file size");
    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 };
  },

  // Complete the multipart upload
  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 };
  },

  // Abort the upload and clean up the uploaded parts
  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"; // Replace with your own login check
    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: "Upload request failed" }));
  }
}).listen(3000);
```

Security notes:

- Generate object keys on the server; do not use client-supplied paths directly, to avoid overwriting other people's files;
- Endpoints must verify the login state, and multipart endpoints must verify that the object key belongs to the current user;
- Once `ContentLength` is signed, the upload size must match the declared size, or S4 returns 403;
- You can also add `x-bitiful-max-requests=1` to prevent a URL from being reused. See [Presigned URLs](https://docs.bitiful.com/en/developer/s3/presigned-url.md).

## Upload small files

First write a function that calls your server's API:

```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();
}
```

Then upload the file; `onProgress` receives progress from 0 to 1:

```javascript title="upload.js"
// fetch cannot report upload progress, so use XMLHttpRequest here
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("Network error or request blocked by CORS"));
    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"; // exported from 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("Upload complete", key);
  });
</script>
```

> **Info**
>
> When you send a `File` directly with XMLHttpRequest or fetch, the browser automatically adds the `Content-Type` it detected. If ContentType was not specified when signing, this header is not part of the signature and the upload works normally; S4 stores it as the object type. To have S4 [detect the type automatically](https://docs.bitiful.com/en/best-practice/auto-detect-mime.md), send content without a type, for example `file.slice(0, file.size, "")`.

## Upload large files

Use multipart upload for files larger than 100 MB: uploading parts concurrently is faster, and a failed part is the only one you need to retry.

```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; // Up to 3 attempts per part
          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;
  }
}
```

Notes:

- Each part is 5 MiB to 20 GiB (the last part can be smaller), with up to 10000 parts;
- Completing the upload requires each part's `ETag`; if the browser cannot read it, CORS is not exposing `ETag`;
- Call abort on failure or cancellation; incomplete parts are retained and consume storage;
- Presigned URLs expire; for very large files, extend the validity period appropriately, or request URLs in batches.

## Download

Have the server generate a presigned URL with `GetObject` and return it to the frontend, which navigates to it directly:

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

When you download through the bucket's default domain, the browser saves the file instead of opening it. To specify the file name, add `ResponseContentDisposition` when signing. To display images or videos directly in a page, use a [CDN domain](https://docs.bitiful.com/en/cdn/intro.md).

## FAQ

<details>
<summary>The console shows a CORS error</summary>

First check the real status code in the network panel. Error responses such as 403 can also be displayed by the browser as CORS errors. Make sure the origin, protocol, and port match the CORS rules, and test in an incognito window after changing the rules.

</details>

<details>
<summary>Upload returns 403 SignatureDoesNotMatch</summary>

`ContentType` was specified when signing but the upload sent a different value; or the file size does not match `ContentLength`; or the URL was escaped in transit (`&` became `&amp;`).

</details>

<details>
<summary>How do I upload from a mini program</summary>

The WeChat mini program API `wx.uploadFile` supports only POST forms. You can use `wx.request` to send an `ArrayBuffer` with PUT, which suits small files; add the domain to the legal domains in the mini program admin console.

</details>

<details>
<summary>Can I use the AWS SDK in the browser</summary>

Technically yes, but it requires a secret key, and S4 does not support STS temporary credentials, so use presigned URLs instead.

</details>

## Related documentation

[**Presigned URLs and extensions**](https://docs.bitiful.com/en/developer/s3/presigned-url.md)

Full reference for request limits, rate limits, Simul-Transfer, and other parameters.

[**Error codes and troubleshooting**](https://docs.bitiful.com/en/developer/s3/errors.md)

Checklists for 403, SignatureDoesNotMatch, and other issues.

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

Support status and differences for each operation.

[**Upload files securely from the client**](https://docs.bitiful.com/en/best-practice/web-uploads.md)

Recommended practices for direct uploads from browsers and apps.
