Skip to content
Console

Upload files securely from the client

Why we don't recommend uploading with client-side SDKs such as the JavaScript SDK

  1. Your ak / sk can be exposed if the client is decompiled.
  2. It isn't flexible enough.

Security best practice: never hand out ak / sk through an API.

A better approach

Generate a presigned URL on the backend and return it through your API

The frontend can send a PUT request directly to the presigned URL. This gives you several benefits:

  1. More secure: your critical AccessKey and SecretKey can never leak through exposed client code or decompilation.
  2. More flexible: by explicitly specifying Content-Type and Content-Length, you prevent a tampered client from bypassing your business rules.
  3. Lower cost: the server hands out presigned URLs in one place, so client developers only need to make a PUT HTTP request. They don't have to learn and debug the S3 SDK in different languages. (In practice, each language version of the AWS SDK is maintained by a different team, and their conventions and features vary widely, which hurts project stability.)
  4. High performance: upload requests still go directly to Bitiful S4, with no relay through your server.

How it works

Generate a presigned upload URL through your backend API: putObject-presigned-url

Have your backend (Go, Python, PHP, Node.js) call the appropriate SDK to generate a presigned URL authorized for the PutObject method, and pass it to the JavaScript on your web page.

The client sends a PUT request to putObject-presigned-url to upload the file

The JavaScript uses an HTTP client library (such as axios) to PUT the local file to the presigned PutObject URL described above.

Presigned URL API

Bitiful has open-sourced a full-featured, self-hosted presigned URL API project. It's stateless, so you can quickly plug it into your existing system as a microservice.

Github: https://github.com/bitiful/s3-presigned-api-server

Examples: generating PutObject presigned URLs in different backend languages

import boto3
from flask import Flask
from flask import render_template_string
from flask import request

app = Flask(__name__)

@app.get('/s3_upload_url')
def get_upload_url():
    # Config
    s3endpoint = 'https://s3.bitiful.net' # Use the value from the "Endpoint" label at the bottom of the "Bucket settings" page in the console
    s3region = 'cn-east-1'
    s3accessKeyId = '<--sub-account accessKey-->' # Create a sub-account in the console, then create an accessKey for it
    s3SecretKeyId = '<--sub-account secretKey-->' # Important: when you create a sub-account, you must grant it specific permissions manually!

    # Connect to S3
    client = boto3.client(
        's3',
        aws_access_key_id = s3accessKeyId,
        aws_secret_access_key = s3SecretKeyId,
        endpoint_url = s3endpoint,
        region_name = s3region
    )
    url = client.generate_presigned_url(
        'put_object',
        Params={
            'Bucket': '<--Bitiful bucket name-->',
            'Key': request.args.get('key'),
        },
        ExpiresIn=3600
    )
    return {'url': url}

Frontend upload example

upload_demo.web.html
<!DOCTYPE html>
<html>
<head>
  <title>S3 File Upload</title>
</head>
<body>
<div>
  <h1>S3 File Upload</h1>
  <input type="file" id="file">
  <button onclick="handleClick()">Upload</button>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.min.js"></script>
<script>
    let file;
    let fileContent;

    const fileInput = document.getElementById('file');
    const fileReader = new FileReader();

    fileInput.addEventListener('change', function (event) {
        file = event.target.files[0];
        console.log("file is: ", file);
        fileReader.readAsArrayBuffer(file);
    });

    fileReader.onload = function (event) {
        fileContent = event.target.result;
        // console.log("fileContent is: ", fileContent);
    };

    function handleClick() {
        console.log('click');

        const url = `/s3_upload_url`;
        const params = {key: '1.jpg'};

        axios.get(url, {params: params})
            .then(function (res) {
                console.log(res);
                const url = res.data.url;
                const config = {
                    headers: {
                        'Content-Type': null,
                    },
                };
                axios.put(url, file, config)
                    .then(function (res) {
                        console.log("res is: ", res);
                    });
            });

    }
</script>

</body>
</html>

The JavaScript above sets Content-Type to an empty value when it sends the PUT request. We recommend using Bitiful's exclusive automatic MIME detection feature.