boto3 upload_file vs put_object vs upload_fileobj: Which to Use, Progress, Speed, and Fix S3 Files That Download Instead of Opening (Content-Type)

Logeshwaran
—

In boto3, upload_file uploads a file from disk using the managed transfer layer: it switches to multipart upload automatically above 8 MB, uploads parts in parallel, retries failed parts, can report progress, and works for files of any size, but returns nothing. upload_fileobj does the same from an open file or in-memory stream. put_object is a single API call: it sends bytes or a file object in one request (up to 5 GB), returns the response (ETag, version ID), and is the simplest choice for small content you already have in memory. Rule of thumb: files on disk, use upload_file; small strings or bytes, use put_object. One trap catches both: boto3 does not set Content-Type for you, so uploaded HTML, images and PDFs are stored as binary/octet-stream and download instead of opening in the browser; pass ContentType (in ExtraArgs for upload_file). Below: code for each method, ExtraArgs and TransferConfig, progress bars, content types, metadata and encryption, presigned uploads, errors, and the same choices in the CLI and JavaScript.

Jake built a small script to publish the shop's weekly newsletter as an HTML page in S3. The upload worked, the link worked, and clicking it downloaded a file called newsletter.html instead of showing the page. Ethan checked the object in the console: content type binary/octet-stream. Nothing was wrong with the HTML; S3 had simply been told nothing about what kind of file it was, so it served it as an anonymous blob and the browser played safe. One extra argument fixed it, and choosing the right upload method fixed the next problem, a 6 GB backup that would not go up at all.

⚡ Quick Answer

• File on disk: s3.upload_file(path, bucket, key), any size. Code.

• Bytes or a string: s3.put_object(Bucket=..., Key=..., Body=data), up to 5 GB. Code.

• Downloads instead of opening? Set ContentType. Fix.

• Progress bar, speed: Callback and TransferConfig. Tuning.

Comparison table · upload_fileobj · Metadata and encryption · Presigned uploads · Errors.

New to boto3 or S3 permissions? The cards below cover boto3 errors, the 5 GB limit, bucket access and multipart uploads.

🧭 NEW HERE? READ THESE FIRST

New to boto3 or uploading to S3? These five pages give you the background this one builds on:

📌 Bookmark this; the comparison table and the Content-Type fix are the parts you will come back for.

Before you start: install boto3 and give it credentials

boto3 is the AWS SDK for Python: the library your script imports to talk to S3 and every other AWS service. It installs like any Python package, ideally inside a virtual environment so each project keeps its own versions:

💻 Where to run these commands

Easiest: AWS CloudShell, nothing to install. Sign in to the AWS Management Console, choose your Region at the top right, then click the CloudShell icon (a small >_ terminal symbol) in the top bar, or type CloudShell in the search box and open it. When the $ prompt appears, paste a command and press Enter. CloudShell already has the AWS CLI, uses your console permissions and costs nothing extra.

On your own computer: install AWS CLI version 2 (installers for Windows, macOS and Linux are on the AWS CLI page), run aws configure once (or aws configure sso if your company signs in through single sign-on), and check it works with aws sts get-caller-identity. Then paste commands into Terminal on Mac or Linux, or PowerShell or Command Prompt on Windows.

Windows tip: a line ending in a backslash ( \ ) continues on the next line in CloudShell, Mac and Linux. In PowerShell use a backtick ( ` ) instead, in Command Prompt a caret ( ^ ), or simply join the lines into one. JSON inside single quotes works as shown in CloudShell; on Windows, save the JSON in a file and pass it as file://name.json.

Python examples: save the code in a file such as script.py, install the AWS SDK with pip install boto3, and run python script.py (python3 on Mac and Linux). It uses the same credentials as the AWS CLI; CloudShell has Python and boto3 ready.

Replace example values such as my-bucket, my-function, 111122223333 (an account ID) and us-east-1 with your own.

# Windows 11 (PowerShell)
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install boto3

# Mac and Linux
python3 -m venv .venv
source .venv/bin/activate
pip install boto3

# Check it worked
python -c "import boto3; print(boto3.__version__)"

Installing boto3 gives it no access to anything. It looks for credentials in a fixed order: environment variables, then the shared credentials and config files that aws configure or aws configure sso creates in your home folder, then the role attached to wherever the code runs (an EC2 instance profile, a Lambda execution role, an ECS task role). On your own computer, the easy route is to install the AWS CLI and run aws configure sso or aws configure once; boto3 then finds the same credentials with no code at all. On AWS compute, attach a role and put no keys in the code.

Two quick checks save an afternoon of confusion. boto3.client("sts").get_caller_identity() prints which account and identity your script is really using. And the Region matters less for S3 than for most services, but set one anyway (boto3.client("s3", region_name="us-east-1") or AWS_DEFAULT_REGION), so presigned URLs and new buckets land where you expect. If your credentials work but uploads fail with AccessDenied, the identity needs s3:PutObject on the bucket, which our bucket access guide sets up.

upload_file vs upload_fileobj vs put_object

upload_fileupload_fileobjput_object
InputA file pathAn open binary file or streamBytes, a string or a file object
SizeAny (multipart above 8 MB by default)Any (multipart as needed)Up to 5 GB in one request
Parallel parts and retriesYesYesNo (one request, normal retries)
Progress callbackYesYesNo
ReturnsNoneNoneResponse with ETag, VersionId
OptionsExtraArgs={...}ExtraArgs={...}Direct parameters (ContentType=...)
Errors raisedS3UploadFailedErrorS3UploadFailedErrorClientError
Best forFiles on disk, especially large onesStreams, uploaded web files, in-memory buffersSmall generated content: JSON, text, thumbnails

Under the hood, upload_file and upload_fileobj call put_object for small files and the multipart APIs for big ones. That is why they handle any size, and why they hand back nothing: there may have been dozens of requests. If you need the ETag or version ID of what you just uploaded, either use put_object or call head_object afterwards.

Jake: "So upload_file is put_object with a forklift?"

Ethan: "For big loads, yes. For a sandwich, you just carry it."

Picking the method in four questions:

  1. Is the data a file on disk? Use upload_file.
  2. Is it an open stream or a web upload you do not want to save first? Use upload_fileobj.
  3. Is it small content you built in memory (JSON, text, a thumbnail)? Use put_object.
  4. Do you need the response (ETag, VersionId, checksum) right away? Prefer put_object for small items, or follow a managed upload with head_object.

upload_file: files on disk

import boto3

s3 = boto3.client("s3")

# Simplest form
s3.upload_file("reports/october.pdf", "shop-data", "reports/2026/october.pdf")

# With content type, metadata and encryption
s3.upload_file(
    "site/newsletter.html", "shop-site", "newsletter.html",
    ExtraArgs={
        "ContentType": "text/html; charset=utf-8",
        "CacheControl": "max-age=300",
        "Metadata": {"issue": "42"},
        "ServerSideEncryption": "aws:kms",
    },
)

The arguments are positional in this order: the local file name, the bucket, the key. Mixing up the bucket and the key, or passing s3://bucket/... as the bucket, is a very common first error; our InvalidBucketName guide shows what that looks like. ExtraArgs accepts the same options as the S3 upload APIs (content type, metadata, encryption, storage class, ACL where allowed, tagging, checksums), and rejects unknown keys with an error naming the allowed ones.

Uploading into a "folder". S3 has no real folders: the key is the whole path, and the console draws folders from the slashes in it. To put a file in reports/2026/, include that in the key, and S3 shows the folder as soon as the first object is in it. There is no need to create the folder first. Build keys with forward slashes even on Windows, where your local path uses backslashes:

from pathlib import Path

local = Path(r"C:\shop\reports\october.pdf")
key = f"reports/2026/{local.name}"            # "reports/2026/october.pdf", never a backslash
s3.upload_file(str(local), "shop-data", key)

A backslash in a key is legal, which is the problem: the upload succeeds, and the console then shows one oddly named object instead of a folder. If you see keys like reports\october.pdf in your bucket, a Windows path went straight into the key.

Upload a whole folder, keeping its structure

boto3 has no single "upload this folder" call; that is a job for a short loop. This version keeps the folder structure in the keys, sets each file's content type, and uploads several files at once:

import mimetypes
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import boto3

s3 = boto3.client("s3")
SRC = Path("site")              # local folder
BUCKET, PREFIX = "shop-site", "newsletter/"

def send(path):
    key = PREFIX + path.relative_to(SRC).as_posix()     # keeps sub-folders, forward slashes
    ctype, _ = mimetypes.guess_type(path.name)
    s3.upload_file(str(path), BUCKET, key,
                   ExtraArgs={"ContentType": ctype or "application/octet-stream"})
    return key

files = [p for p in SRC.rglob("*") if p.is_file()]
with ThreadPoolExecutor(max_workers=8) as pool:
    for key in pool.map(send, files):
        print("uploaded", key)

A boto3 client is safe to share between threads, so one client serves all eight workers. relative_to(...).as_posix() is what turns site\img\logo.png on Windows into the key newsletter/img/logo.png. If one file fails, pool.map raises that error when the loop reaches it, so wrap send in a try block if you would rather log failures and carry on.

For a plain copy with no custom logic, the AWS CLI is shorter: aws s3 sync site s3://shop-site/newsletter/ uploads only new or changed files and guesses content types for you. Use the Python loop when you need your own rules, such as skipping drafts, renaming keys or adding metadata per file.

Jake: "So the folder on my desktop ends up as the same folders in S3?"

Ethan: "Same names, same nesting. S3 just stores it as one long name per file."

upload_fileobj: streams and in-memory files

# An open file (binary mode)
with open("backups/db-backup.sql.gz", "rb") as f:
    s3.upload_fileobj(f, "shop-backups", "nightly/db-backup.sql.gz")

# An in-memory buffer, for example a generated image
import io
buf = io.BytesIO(png_bytes)
s3.upload_fileobj(buf, "shop-site", "img/chart.png", ExtraArgs={"ContentType": "image/png"})

# A file uploaded to your web app (Flask/Django give you a file-like object)
s3.upload_fileobj(request.files["photo"], "shop-uploads", f"photos/{uuid4()}.jpg",
                  ExtraArgs={"ContentType": request.files["photo"].mimetype})

The object must be opened in binary mode ("rb"); passing a text-mode file raises an error about strings versus bytes. Like upload_file, it switches to multipart for large streams, so it is the right tool for piping a big upload through your app without saving it to disk first.

Streaming from another website straight into S3. To copy a large file from a URL into a bucket without storing it on your machine, hand the HTTP response's raw stream to upload_fileobj:

import requests

url = "https://example.com/exports/catalog-2026.csv"
with requests.get(url, stream=True, timeout=60) as r:
    r.raise_for_status()
    r.raw.decode_content = True          # undo gzip transfer encoding, if the server used it
    s3.upload_fileobj(r.raw, "shop-data", "imports/catalog-2026.csv",
                      ExtraArgs={"ContentType": "text/csv"})

Memory use stays small however large the file is, because the transfer manager reads one part at a time. The same idea works for any object with a read() method: a compressed stream from gzip.open, a pipe from another process, or a file arriving in a web request.

put_object: small content in one call

import json

resp = s3.put_object(
    Bucket="shop-data",
    Key="prices/today.json",
    Body=json.JSONEncoder().encode(prices),     # str or bytes
    ContentType="application/json",
)
print(resp["ETag"], resp.get("VersionId"))

# Text
s3.put_object(Bucket="shop-data", Key="notes/readme.txt", Body="Hello S3", ContentType="text/plain")

# An empty "folder" marker (a zero-byte key ending in /)
s3.put_object(Bucket="shop-data", Key="exports/2026/")

put_object is one HTTP request: quick for small objects, no extra machinery, and it tells you exactly what was stored (ETag, version, checksum). Past 5 GB it fails with EntityTooLarge, covered in our EntityTooLarge guide; for anything that big, use upload_file. A single large request also restarts from zero if the connection drops, which is another reason to keep it for small content.

Body accepts bytes, a string (sent as UTF-8) or an open binary file. Passing a file object to put_object works, but for anything bigger than a few megabytes, upload_fileobj with the same file is the better choice. Two more parameters are worth knowing here: ChecksumAlgorithm (or ChecksumSHA256 with your own value) for end-to-end integrity checks, and IfNoneMatch="*", which turns the upload into "create only, never overwrite," covered two sections below.

Do not overwrite an existing file: conditional writes

By default, uploading to a key that already exists replaces the object without a word. That is fine for a price list you regenerate every hour, and a disaster for an invoice archive where two processes might pick the same file name. Since 2024, S3 can refuse the write instead:

from botocore.exceptions import ClientError

try:
    s3.put_object(Bucket="shop-archive", Key="invoices/2026/INV-1042.pdf",
                  Body=pdf_bytes, ContentType="application/pdf",
                  IfNoneMatch="*")              # only if no object has this key yet
    print("stored")
except ClientError as e:
    if e.response["Error"]["Code"] == "PreconditionFailed":
        print("INV-1042 already exists; not overwritten")
    else:
        raise

IfNoneMatch="*" means "only if nothing is there." If an object exists, S3 answers with HTTP 412 Precondition Failed and keeps the original untouched. If two uploads race for the same new key at the same moment, one wins and the other gets a conflict error, so you never end up with a silent mix of both.

The opposite check, IfMatch with an ETag, writes only if the object is still the version you last read, which stops two editors from overwriting each other's changes to a shared file. Both checks are on put_object and on completing a multipart upload. With upload_file, the simple pattern for big files is to check first with head_object, accepting the small window between the check and the upload, or to upload under a unique key such as one with a timestamp or UUID in it.

Uploading new versions of the same file

If the bucket has versioning enabled, an upload to an existing key does not replace the old object; it stacks a new version on top, and the old one stays recoverable. Nothing changes in your code: the same upload_file or put_object call simply creates version two, three and so on.

# Turn versioning on once (needs s3:PutBucketVersioning)
s3.put_bucket_versioning(Bucket="shop-data", VersioningConfiguration={"Status": "Enabled"})

resp = s3.put_object(Bucket="shop-data", Key="prices/today.json", Body=new_json)
print("new version:", resp["VersionId"])

# Every version of one key, newest first
for v in s3.list_object_versions(Bucket="shop-data", Prefix="prices/today.json")["Versions"]:
    print(v["VersionId"], v["LastModified"], v["IsLatest"])

To read an older version, pass VersionId to get_object or download_file's ExtraArgs. To restore one, copy it onto the same key, which makes it the newest version again. Versioning costs storage for every version you keep, so pair it with a lifecycle rule that deletes noncurrent versions after, say, 30 or 90 days. Versions are also why put_object is handy for files you regenerate: its response hands you the new VersionId to log, while upload_file would need a head_object call afterwards.

Files download instead of opening: set Content-Type

S3 stores whatever Content-Type you send with the upload and returns it to browsers. boto3 does not guess it from the file name, so without one the object is stored as binary/octet-stream, and browsers download the file instead of displaying it. The AWS CLI's aws s3 cp does guess from the extension, which is why the same file can behave differently depending on how it was uploaded.

The fix, in code that works for any file:

import mimetypes

def upload(path, bucket, key):
    ctype, _ = mimetypes.guess_type(path)
    extra = {"ContentType": ctype or "application/octet-stream"}
    if ctype and ctype.startswith("text/"):
        extra["ContentType"] += "; charset=utf-8"
    s3.upload_file(path, bucket, key, ExtraArgs=extra)

upload("site/newsletter.html", "shop-site", "newsletter.html")   # text/html; charset=utf-8

The content types you will set most often:

FileContentTypeBrowser behavior
.htmltext/html; charset=utf-8Renders the page
.css / .jstext/css / text/javascriptApplied by pages; wrong types are blocked
.jsonapplication/jsonShown or parsed by fetch()
.pdfapplication/pdfOpens in the built-in viewer
.jpg / .png / .webp / .svgimage/jpeg / image/png / image/webp / image/svg+xmlDisplays the image
.mp4video/mp4Plays in the browser
Anything, forced downloadAny type + ContentDisposition="attachment"Saves to disk

Fixing objects that are already uploaded: copy each object onto itself with the new type and MetadataDirective="REPLACE":

s3.copy_object(Bucket="shop-site", Key="newsletter.html",
               CopySource={"Bucket": "shop-site", "Key": "newsletter.html"},
               ContentType="text/html; charset=utf-8", MetadataDirective="REPLACE")

With REPLACE, any custom metadata on the object is replaced too, so pass it again if you had some. For a whole bucket of wrongly typed files:

  1. List the objects with a paginator over list_objects_v2.
  2. Guess each type from the key with mimetypes.guess_type.
  3. Check the current type with head_object and skip objects that are already right.
  4. Copy in place with the new ContentType and MetadataDirective="REPLACE", carrying over existing metadata.
  5. Invalidate the CDN cache if the files are served through CloudFront, so visitors get the new headers.

In the console you can also change it per object: select it, choose Actions, Edit metadata, and set Content-Type. The opposite case, forcing a download for a file that would normally open, uses ContentDisposition="attachment; filename=report.pdf".

Jake: "So the HTML was fine, S3 just didn't know it was HTML?"

Ethan: "Exactly. It stores the label you give it, and boto3 doesn't write labels for you."

Progress bars and speed: Callback and TransferConfig

import os, sys, threading
from boto3.s3.transfer import TransferConfig

class Progress:
    def __init__(self, path):
        self.size = os.path.getsize(path); self.seen = 0; self.lock = threading.Lock()
    def __call__(self, n):
        with self.lock:
            self.seen += n
            sys.stdout.write(f"\r{self.seen / self.size:6.1%}"); sys.stdout.flush()

config = TransferConfig(
    multipart_threshold=64 * 1024 * 1024,   # switch to multipart above 64 MB
    multipart_chunksize=64 * 1024 * 1024,   # part size
    max_concurrency=10,                     # parallel threads
)

path = "backups/full-6gb.tar.gz"
s3.upload_file(path, "shop-backups", "weekly/full.tar.gz", Config=config, Callback=Progress(path))

The callback receives the number of bytes sent since the last call, from several threads, which is why it uses a lock. For fast networks, raising max_concurrency and the chunk size speeds up very large uploads; on slow or shared connections, lowering concurrency avoids timeouts. Our RequestTimeout guide covers uploads that stall.

The defaults, so you know what you are changing: multipart starts at 8 MB, parts are 8 MB, and up to 10 threads run at once. S3 allows at most 10,000 parts per upload, and the transfer manager quietly raises the part size when a file is too big for 10,000 parts of the configured size, so a 200 GB file still uploads with default settings. Raising the chunk size yourself mostly reduces the number of requests, which helps on fast links with high latency.

For very large transfers on big instances, installing boto3[crt] adds the AWS Common Runtime transfer client, which is often faster at saturating a fast network than the default Python threads. It is an optional extra, and your code stays the same.

Interrupted big uploads leave unfinished multipart uploads behind, which are billed as storage until aborted. A lifecycle rule that aborts incomplete multipart uploads after a few days keeps them from piling up; our NoSuchUpload guide explains how to find and clear them.

Multipart upload by hand: when the managed upload is not enough

upload_file does multipart for you, and for nearly everyone that is the right answer. The low-level calls are worth knowing for three cases: uploads that must survive a script restart and resume where they stopped, parts produced by different machines, and data generated in pieces where you never have the whole file at once. The flow has three steps:

PART = 64 * 1024 * 1024                       # every part except the last: 5 MB to 5 GB
mpu = s3.create_multipart_upload(Bucket="shop-backups", Key="weekly/full.tar.gz")
upload_id = mpu["UploadId"]
parts = []
try:
    with open("backups/full.tar.gz", "rb") as f:
        number = 1
        while chunk := f.read(PART):
            r = s3.upload_part(Bucket="shop-backups", Key="weekly/full.tar.gz",
                               UploadId=upload_id, PartNumber=number, Body=chunk)
            parts.append({"PartNumber": number, "ETag": r["ETag"]})
            number += 1
    s3.complete_multipart_upload(Bucket="shop-backups", Key="weekly/full.tar.gz",
                                 UploadId=upload_id, MultipartUpload={"Parts": parts})
except Exception:
    s3.abort_multipart_upload(Bucket="shop-backups", Key="weekly/full.tar.gz", UploadId=upload_id)
    raise

The rules that bite: part numbers run from 1 to 10,000; every part except the last must be at least 5 MB; each part can be up to 5 GB; and the finished object can be up to 50 TB. The object does not exist until complete_multipart_upload succeeds, so readers never see half a file. And an upload that is neither completed nor aborted keeps its parts in the bucket, billed as storage and invisible in the normal object list, which is why the abort in the error path and a lifecycle rule for incomplete uploads both matter.

To resume after a crash, save the UploadId somewhere, call list_parts with it on restart to see which parts arrived, and upload only the missing ones before completing. That resumable behavior is the main thing the managed upload_file does not offer, and the main reason to write this loop yourself.

Metadata, encryption, storage class and checksums

  • Metadata: "Metadata": {"issue": "42"} becomes x-amz-meta-issue; keep values short ASCII strings.
  • Encryption: buckets encrypt by default with SSE-S3; "ServerSideEncryption": "aws:kms" plus "SSEKMSKeyId" uses your KMS key, which the uploading role must be allowed to use.
  • Storage class: "StorageClass": "STANDARD_IA" or "GLACIER_IR" for backups you rarely read.
  • Tagging: "Tagging": "project=shop&team=ops" for lifecycle rules and cost reports.
  • Checksums: "ChecksumAlgorithm": "SHA256" (or CRC32) asks S3 to verify integrity end to end; current boto3 versions add a default checksum on uploads automatically.
  • ACLs: most buckets now have ACLs disabled (Bucket owner enforced), so passing "ACL": "public-read" fails; use a bucket policy instead, as our bucket access guide shows.

Check that an upload really worked

Because upload_file returns None, people often wonder whether it worked. The rule is simple: if it returned without raising an exception, S3 has the complete object. For extra certainty, or for a log entry, ask S3 what it stored:

import os

path, key = "backups/full.tar.gz", "weekly/full.tar.gz"
s3.upload_file(path, "shop-backups", key)

head = s3.head_object(Bucket="shop-backups", Key=key, ChecksumMode="ENABLED")
assert head["ContentLength"] == os.path.getsize(path), "size mismatch"
print("stored", head["ContentLength"], "bytes,",
      "type", head["ContentType"], "version", head.get("VersionId"))

head_object reads only the object's details, not its contents, so it is quick and cheap even for a 6 GB backup. Comparing the size catches truncated uploads from code that wrote the wrong buffer. With ChecksumMode="ENABLED", the response also carries the stored checksum, if one was recorded, which you can compare with your own.

Do not compare the ETag with an MD5 of your file for multipart uploads. For single-request uploads with default encryption, the ETag is often the MD5 of the content, but for multipart uploads it is a checksum of the parts' checksums with a part count on the end, such as "9b2cf535f27731c974343645a3985328-12". A script that expects an MD5 will report a perfectly good upload as corrupted.

Uploading to S3 from AWS Lambda

Lambda functions upload to S3 all the time, and the same three methods apply, with two Lambda-specific points.

Use memory or /tmp, not a fixed path. The only writable folder in a Lambda function is /tmp, which holds 512 MB by default and can be raised to 10,240 MB in the function's configuration. For generated reports, build the content in memory and use put_object or upload_fileobj with a BytesIO; for larger files, write to /tmp and use upload_file. Files left in /tmp can still be there on the next invocation of the same instance, so delete them when you are done.

import csv, io
import boto3

s3 = boto3.client("s3")              # created once, outside the handler, and reused

def handler(event, context):
    buf = io.StringIO()
    writer = csv.writer(buf)
    writer.writerow(["sku", "price"])
    for item in event.get("items", []):
        writer.writerow([item["sku"], item["price"]])
    s3.put_object(Bucket="shop-data", Key="exports/prices.csv",
                  Body=buf.getvalue(), ContentType="text/csv; charset=utf-8")
    return {"saved": "exports/prices.csv"}

Permissions come from the execution role. The function's role needs s3:PutObject on the bucket and key prefix, plus kms:GenerateDataKey if the bucket uses a customer-managed KMS key. No access keys belong in the code or environment variables. And if the function runs in a VPC without internet access, it needs an S3 gateway endpoint to reach S3 at all, which is free and avoids NAT charges.

Large uploads also need time: the default 3-second timeout is far too short for anything but tiny files, so raise it to match the biggest upload you expect.

Letting a browser upload directly: presigned URLs

For user uploads, a common pattern is to let the browser send the file straight to S3, so it never passes through your server. Your server signs a short-lived URL:

# A presigned PUT: the browser sends the file body to this URL
url = s3.generate_presigned_url(
    "put_object",
    Params={"Bucket": "shop-uploads", "Key": "photos/abc123.jpg", "ContentType": "image/jpeg"},
    ExpiresIn=600,
)

# Or a presigned POST, which can limit size and type with conditions
post = s3.generate_presigned_post(
    "shop-uploads", "photos/abc123.jpg",
    Conditions=[["content-length-range", 1, 10_000_000], {"Content-Type": "image/jpeg"}],
    ExpiresIn=600,
)

If the URL is signed with a ContentType, the browser must send exactly that header, or S3 rejects it with SignatureDoesNotMatch (our SignatureDoesNotMatch guide covers it). The bucket also needs a CORS rule allowing PUT or POST from your site.

Which one to choose? A presigned PUT is the simplest for the browser: one fetch(url, {method: "PUT", body: file}). A presigned POST takes a few more lines on the browser side (a form with the returned fields), but its conditions let S3 itself refuse files over a size limit or of the wrong type, which a PUT URL cannot do. For public sign-up forms where anyone could upload, the POST's size limit is worth the extra lines. Either way, keep ExpiresIn short, generate a fresh key per upload so users cannot overwrite each other, and remember that the URL carries the permissions of whoever signed it.

Jake: "So our server never touches the photo itself?"

Ethan: "It just signs a permission slip. The photo goes straight from the customer's phone to S3."

Upload errors, fixed

  • S3UploadFailedError: Failed to upload ... An error occurred (AccessDenied): the role lacks s3:PutObject on that key, or cannot use the KMS key for SSE-KMS. Catch boto3.exceptions.S3UploadFailedError for upload_file, and botocore.exceptions.ClientError for put_object; our boto3 error handling guide shows both.
  • EntityTooLarge from put_object: over 5 GB in one request; switch to upload_file.
  • AccessControlListNotSupported: you passed an ACL to a bucket with ACLs disabled; remove it.
  • ValueError: Invalid extra_args key: a misspelled or unsupported option in ExtraArgs; the message lists the allowed keys.
  • TypeError about str and bytes: a text-mode file passed to upload_fileobj; open it with "rb".
  • FileNotFoundError: the local path is relative to where Python runs, not where the script lives; build it with pathlib from __file__.
  • Upload "works" but the file opens wrongly: missing or wrong Content-Type, as above.

What uploads cost

Uploading data into S3 is free in terms of bandwidth: AWS does not charge for data transferred in from the internet. What you pay for is requests and storage, and the method you choose changes the request count:

  • Requests: uploads are billed as PUT requests, about $0.005 per 1,000 in S3 Standard in US Regions. A put_object is one request. A multipart upload is one request per part plus the start and finish, so a 6 GB file in 8 MB parts is roughly 770 requests, still well under a cent.
  • Many small files are where request costs show up: a million tiny uploads cost about $5 in requests alone. If you upload thousands of small records a day, batching them into fewer, larger objects saves money and makes them faster to read later.
  • Storage: S3 Standard is about $0.023 per GB per month for the first 50 TB in US Regions. Cheaper classes such as Standard-IA and Glacier Instant Retrieval suit backups, but they bill a minimum storage time (30 and 90 days) and Standard-IA bills small objects as at least 128 KB, so they are wrong for short-lived or tiny files.
  • Abandoned multipart uploads are billed as storage until aborted, which is why the lifecycle rule mentioned earlier is worth adding to every bucket that receives large uploads.

For Jake's shop, the whole upload bill is pennies: a weekly 6 GB backup, a few hundred newsletter files and an hourly price list. The storage of the backups is the only line worth watching, and a lifecycle rule moving older backups to a cheaper class keeps it small.

Upload safety: credentials, public access and user files

Most S3 incidents start with an upload, not a download. A few habits keep yours out of the news:

  • No keys in code. Scripts on your computer use the credentials from aws configure; code on AWS uses a role. Access keys pasted into a script end up in Git history, and from there in someone else's hands.
  • Leave Block Public Access on. New buckets block public access by default. If files must be public, such as a website, serve them through CloudFront with the bucket kept private, rather than opening the bucket itself.
  • Never trust a user's file name. Generate the key yourself (a UUID plus the right extension), so nobody can overwrite another user's file or plant a key with odd characters. Keep the original name in metadata if you need to show it.
  • Check type and size before accepting. Limit size with a presigned POST condition or in your app, and check the content type you allow. A "photo" upload that is really an HTML file, served from your domain, is a classic way to attack your visitors.
  • Scan files from strangers. If the public can upload, turn on malware scanning for the bucket, such as Amazon GuardDuty Malware Protection for S3, which checks new objects as they arrive and tags the result.

Jake: "Even the newsletter bucket?"

Ethan: "That one's fine: only our script writes to it. The customer photo uploads are the ones that get all five rules."

boto3.client vs boto3.resource for uploads

Older tutorials often upload through boto3.resource("s3") instead of boto3.client("s3"). Both work, and the managed upload methods exist on both:

# Client: what this page uses
s3 = boto3.client("s3")
s3.upload_file("report.pdf", "shop-data", "reports/report.pdf")

# Resource: the same upload, object-style
s3r = boto3.resource("s3")
s3r.Bucket("shop-data").upload_file("report.pdf", "reports/report.pdf")
s3r.Object("shop-data", "notes/readme.txt").put(Body="Hello S3", ContentType="text/plain")

The resource interface reads nicely, but it is frozen: AWS is no longer adding features to it, so new S3 options arrive on the client first and may never reach resources. The client maps one-to-one onto the S3 API, which also makes its error messages and parameters match what you read elsewhere. For new code, use the client; there is no need to rewrite working resource code, since it keeps working.

The two mix freely. s3r.meta.client gives you the client inside a resource, which is the quick way to reach a newer parameter from older resource-based code.

The reverse: download_file, download_fileobj and get_object

Downloads mirror uploads exactly, method for method:

# To a file on disk (managed: parallel ranges, retries, any size)
s3.download_file("shop-data", "reports/2026/october.pdf", "october.pdf")

# Into an open binary file or buffer
import io
buf = io.BytesIO()
s3.download_fileobj("shop-data", "prices/today.json", buf)
data = buf.getvalue()

# One request, when you want the body and the response details together
resp = s3.get_object(Bucket="shop-data", Key="prices/today.json")
text = resp["Body"].read().decode("utf-8")

Note the argument order: download_file takes the bucket, then the key, then the local file name, the reverse of upload_file. Swapping them is the classic cause of a 404 for a file you can see in the console. Reading the body of get_object in other languages is covered in our GetObject guide.

Downloading a whole folder is the same loop as uploading one, run backwards: list every key under the prefix, recreate the folders locally, and download each file.

from pathlib import Path

def download_prefix(bucket, prefix, dest):
    pages = s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix)
    for page in pages:
        for obj in page.get("Contents", []):
            key = obj["Key"]
            if key.endswith("/"):                     # folder marker, nothing to download
                continue
            target = Path(dest) / key[len(prefix):]
            target.parent.mkdir(parents=True, exist_ok=True)
            s3.download_file(bucket, key, str(target))

download_prefix("shop-data", "reports/2026/", "reports-2026")

The paginator matters: a single list_objects_v2 call returns at most 1,000 keys, so without it a big folder downloads only partly and silently. For a one-off copy, aws s3 cp s3://shop-data/reports/2026/ reports-2026 --recursive or aws s3 sync does the same from the terminal. S3 has no "download folder as zip" button; if someone needs a single file, zip the downloaded folder locally.

Can you append to a file in S3?

Not to ordinary S3 objects. An object is written whole: to add a line to a log file in a normal bucket, you read it, add the line, and upload the whole thing again, or, far better, write each batch of lines as its own small object with a timestamp in the key and combine them when you read. That second pattern is how most logging systems store data in S3, and it never has two writers fighting over one file.

The exception is S3 Express One Zone, the high-performance storage class in directory buckets. There, put_object can append to an existing object by passing a write offset equal to the object's current size, up to 5 GB per append, with each append billed as a normal PUT request. It suits data that grows over time, such as log files or video segments, but it is limited to directory buckets in one Availability Zone, so it is not a general answer for everyday buckets.

Jake: "So I can't just add today's sales to the end of the sales file?"

Ethan: "Not in our bucket. Each day gets its own small file, and the report reads them all. It's actually tidier."

The same choices in the CLI and JavaScript

  • AWS CLI: aws s3 cp file s3://bucket/key behaves like upload_file (multipart, parallel, content type guessed); aws s3api put-object --bucket b --key k --body file behaves like put_object. Add --content-type to either to set the type yourself.
  • JavaScript SDK v3: PutObjectCommand is the single request; the Upload class from @aws-sdk/lib-storage is the managed, multipart, parallel version with progress events. Reading files back is covered in our GetObject guide.

The JavaScript managed upload looks like this, with a progress event in place of boto3's callback:

import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";
import { createReadStream } from "node:fs";

const upload = new Upload({
  client: new S3Client({}),
  params: { Bucket: "shop-backups", Key: "weekly/full.tar.gz",
            Body: createReadStream("backups/full.tar.gz"), ContentType: "application/gzip" },
  queueSize: 4,                       // parts in parallel
  partSize: 64 * 1024 * 1024,         // at least 5 MB
});
upload.on("httpUploadProgress", (p) => console.log(p.loaded, "of", p.total));
await upload.done();

Like boto3, the JavaScript SDK does not guess ContentType from the file name, so the same "downloads instead of opening" problem appears there unless you set it.

Whichever tool you use, the same two decisions come up: one request or a managed multipart transfer, and which content type to store. Make both deliberately, and uploads behave the same from your script, your CI pipeline and your web app.

Frequently asked questions

What is the difference between upload_file and put_object in boto3?

upload_file uploads a file from disk with automatic multipart, parallel parts, retries and progress, for any size; put_object sends content in one request up to 5 GB and returns the response.

When should I use put_object instead of upload_file?

For small content you already have in memory, such as JSON or text, or when you need the ETag or version ID from the response.

What is upload_fileobj in boto3?

The managed upload for an open binary file or stream, such as an in-memory buffer or a file uploaded to a web app.

Why does my S3 file download instead of opening in the browser?

Its Content-Type is binary/octet-stream because boto3 does not set one. Pass ContentType when uploading, or update it with copy_object and MetadataDirective REPLACE.

How do I set Content-Type with upload_file?

Pass ExtraArgs={"ContentType": "text/html"}, or guess it with mimetypes.guess_type.

Does upload_file use multipart upload?

Yes, automatically, for files above the multipart threshold (8 MB by default), with parts uploaded in parallel.

What is the maximum size for put_object?

5 GB in a single request; use upload_file or multipart upload for larger files, up to 50 TB per object.

How do I show upload progress in boto3?

Pass a Callback function to upload_file or upload_fileobj; it receives the bytes sent since the last call.

How do I make boto3 uploads faster?

Use a TransferConfig with a larger max_concurrency and multipart_chunksize for big files on fast networks.

What does upload_file return?

None. Use put_object or head_object if you need the ETag or version ID.

How do I add metadata to an S3 upload in boto3?

Pass Metadata={"key": "value"} in ExtraArgs or to put_object; it is stored as x-amz-meta-key.

How do I upload a string to S3 with boto3?

s3.put_object(Bucket=..., Key=..., Body="text", ContentType="text/plain").

How do I upload with KMS encryption in boto3?

Pass ServerSideEncryption="aws:kms" and SSEKMSKeyId; the role must be allowed to use the key.

How do I let users upload directly to S3 from a browser?

Generate a presigned PUT URL or presigned POST on your server with boto3 and give it to the browser; add a CORS rule to the bucket.

What exception does upload_file raise?

boto3.exceptions.S3UploadFailedError, which wraps the underlying ClientError.

How do I create a folder in S3 with boto3?

Folders are key prefixes; put_object with a Key ending in a slash creates an empty marker, but uploading a key such as exports/file.csv is enough.

Does the AWS CLI set Content-Type automatically?

Yes. aws s3 cp guesses it from the file extension, unlike boto3; use --content-type to override.

How do I install boto3?

Run pip install boto3, ideally inside a virtual environment. Credentials come separately, for example from aws configure or an attached IAM role.

How do I upload a file to a folder in S3 with boto3?

Put the folder in the key: upload_file("a.pdf", "bucket", "reports/2026/a.pdf"). S3 shows the folder automatically; use forward slashes.

How do I upload a whole folder to S3 with Python?

Walk the folder with pathlib's rglob, build each key from the relative path with as_posix(), and call upload_file for each file, optionally in a thread pool.

How do I stop boto3 from overwriting an existing S3 object?

Use put_object with IfNoneMatch="*". If the key already exists, S3 returns 412 PreconditionFailed and keeps the original.

How do I check that a boto3 upload succeeded?

If upload_file returns without an exception, it succeeded. For proof, call head_object and compare ContentLength with the local file size.

What is the difference between boto3.client and boto3.resource?

The client maps directly to the S3 API and gets new features; the resource interface is object-style but no longer receives new features. Both can upload.

How do I download a file from S3 with boto3?

s3.download_file(bucket, key, local_path). Note the order is the reverse of upload_file.

Can I append to an existing S3 object?

Not in normal buckets: rewrite the object or write a new one per batch. S3 Express One Zone directory buckets support appends with a write offset.

How much does it cost to upload files to S3?

Data coming in is free. You pay about $0.005 per 1,000 PUT requests in S3 Standard in US Regions, plus storage, so many tiny files cost more than a few big ones.

Can I resume an interrupted S3 upload in boto3?

Not with upload_file. Use the low-level multipart calls, save the UploadId, check list_parts after a restart, and upload only the missing parts.

How do I upload to S3 from a Lambda function?

Use put_object or upload_fileobj from memory, or write to /tmp and use upload_file. The execution role needs s3:PutObject.

For readers preparing for an AWS certification

We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.

Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026) • Solutions Architect – Associate (SAA-C03) • CloudOps Engineer – Associate (SOA-C03).

Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:

1. What is the largest object you can upload to S3 in a single PUT request?

5 GB; larger objects need multipart upload.

2. When should you use multipart upload for S3?

For large objects (recommended from about 100 MB): parts upload in parallel and failed parts can be retried alone.

3. Users must upload files directly from browsers to S3 without passing through the app server. What do you use?

Presigned URLs (PUT or POST) generated by the server.

4. Files uploaded to S3 download instead of displaying in the browser. What is wrong?

The objects were stored without the correct Content-Type metadata.

5. Which S3 lifecycle action removes leftover parts of failed multipart uploads?

AbortIncompleteMultipartUpload.

6. Which IAM action does an application need to upload objects to S3?

s3:PutObject (and kms:GenerateDataKey for SSE-KMS buckets).

7. How can you speed up uploads of large files to a distant S3 bucket?

Use multipart upload with parallel parts, and S3 Transfer Acceleration if the distance is the bottleneck.

Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.

πŸ“š ALSO READ

Where to go next, from reading objects back to signature errors:

📌 Bookmark this; the comparison table and the Content-Type fix are the parts you will come back for.

The newsletter script now guesses each file's type, so HTML pages open, images show and PDFs preview in the browser. The 6 GB weekly backup goes up with upload_file, a 64 MB chunk size and a progress bar, in a few minutes instead of failing at 5 GB. And the small price list Jake regenerates every hour uses put_object, because he wanted its version ID in his logs. Three methods, three jobs, no more guessing.

📌 If you keep one line from this page

Use upload_file for files on disk (any size, multipart, progress), upload_fileobj for streams, and put_object for small in-memory content up to 5 GB, and always pass a ContentType so browsers open your files instead of downloading them.

ExtraArgs for options · TransferConfig for speed · Callback for progress · copy_object to fix old types.

Revision note. Written October 19, 2026. S3 stores exactly what you tell it about a file, including what kind of file it is.

Related