A 3 GB upload over hotel Wi-Fi fails at 87 percent, and the user has to start over. That is the moment a single big POST stops being good enough. Here is the small, library free protocol I use in my file host (Flask on the server, plain JavaScript in the browser) to upload large files in pieces and pick up where they left off after a dropped connection.
Why not one big request
- Body limits. Reverse proxies and platforms cap request bodies. Raising the cap to several gigabytes for one endpoint is possible, but every failure then costs the whole upload.
- Flaky connections. Phones switch networks, laptops sleep, Wi-Fi drops for two seconds. With one request, any of that means starting from zero.
- Progress you can trust. With pieces, the server confirms what it actually stored, so the progress bar reflects bytes on disk, not bytes that left the browser.
The protocol: init, chunks, finish
Three endpoints:
POST /api/upload/initwith the file name and size. The server checks the quota, creates an upload row and an empty part file, and returns anupload_idplus thechunk_size(16 MB by default, configurable).POST /api/upload/<id>/chunk?offset=Nwith the raw bytes of one piece as the body. The server answers with how many bytes it has now.POST /api/upload/<id>/finishonce everything is there. The server checks the size and turns the part file into a real upload.
The important part is that offset. The server stores how many bytes it has received, and a chunk is only accepted if it starts exactly there.
The server side
@bp.route("/api/upload/<upload_id>/chunk", methods=["POST"])
@login_required
def api_upload_chunk(upload_id):
up = _load_upload(upload_id)
if up is None:
return jsonify(ok=False, error="Upload not found. Please start again."), 404
part = _part_path(upload_id)
received = up["received"]
offset = request.args.get("offset", -1, type=int)
if offset != received:
# The browser is out of sync, tell it where we are
return jsonify(ok=False, received=received, error="Wrong offset."), 409
limit = current_app.config["CHUNK_MB"] * 1024 * 1024 + 1024 * 1024
written = 0
with open(part, "r+b" if part.exists() else "wb") as fh:
fh.truncate(received) # drop leftovers of an interrupted chunk
fh.seek(received)
while True:
buf = request.stream.read(1024 * 1024)
if not buf:
break
written += len(buf)
if written > limit or received + written > up["size_bytes"]:
fh.truncate(received)
return jsonify(ok=False, error="Too much data sent."), 400
fh.write(buf)
get_db().execute("UPDATE uploads SET received = ? WHERE id = ?", (received + written, upload_id))
return jsonify(ok=True, received=received + written)
Three details do most of the work:
truncate(received)before writing. If a previous chunk was cut off halfway, the part file has some extra bytes the database doesn't know about. Cutting the file back to the confirmed length makes every retry start from a clean state.- Reading
request.streamin 1 MB steps. The chunk never sits in memory as a whole, and the size checks happen while reading, so a client can't push more than one chunk or more than the declared file size. - 409 with the real position. When the offsets don't match, the answer isn't just an error. It tells the browser where to continue.
finish then compares the stored count and the file size on disk with the declared size, and only if all three match it moves the part file into place with Path.replace, which is a rename and doesn't copy anything.
The browser side
fetch still can't report upload progress, so each chunk goes out with XMLHttpRequest:
function sendChunk(item, offset, blob, onProgress) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload/" + item.uploadId + "/chunk?offset=" + offset);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.upload.onprogress = function (ev) { onProgress(ev.loaded); };
xhr.onload = function () {
var data = {};
try { data = JSON.parse(xhr.responseText); } catch (e) {}
if (xhr.status === 200 && data.ok) return resolve(data.received);
if (xhr.status === 409 && typeof data.received === "number") return resolve(data.received);
var err = new Error(data.error || "Error " + xhr.status);
err.fatal = xhr.status >= 400 && xhr.status < 500;
reject(err);
};
xhr.onerror = function () { reject(new Error("Connection lost")); };
xhr.send(blob);
});
}
A 409 is treated as success: the browser simply continues from the offset the server reported. Everything else in the 4xx range is fatal (wrong file, quota, not logged in), so retrying would not help. Network errors and 5xx answers are retried.
The loop around it slices the file with file.slice(offset, offset + chunkSize), which doesn't read anything into memory until the request is sent, and backs off on errors:
}, function (err) {
if (err.fatal || tries >= 5) throw err;
tries++;
setStatus(item, "Connection lost, retry " + tries + " of 5");
return wait(1000 * Math.pow(2, tries - 1)).then(next);
});
That is 1, 2, 4, 8 and 16 seconds, about half a minute in total, which covers most network switches and short drops. After every successful chunk the counter goes back to zero.
The proxy in front
With nginx in front of Flask, two settings matter:
client_max_body_size 64m; # a few times the chunk size
proxy_request_buffering off; # pass uploads straight through
Without proxy_request_buffering off, nginx first receives each chunk completely, often into a temporary file, before passing it on. That adds disk writes and a delay before the app sees any data.
Cleaning up
Uploads that are started and never finished leave part files behind. Instead of a separate job, the init endpoint runs a cleanup now and then (with a 5 percent chance per call) and deletes part files older than two days. Pending uploads from the last two days also count toward the user's quota, so nobody can park unlimited data in half finished uploads.
What I would add next
The upload survives connection drops, but not a closed tab. Storing the upload_id with a fingerprint of the file (name, size, last modified) in localStorage would let the page offer "continue the upload" after a reload. If you need that today, the tus protocol and its libraries solve exactly this.
This is the uploader behind Vidlify, the file and video host I built. If you try the protocol in your own app, I'd like to hear how it holds up on bad connections.
Comments
Join the discussionNo comments yet. Be the first to comment.
