To upload an image or other media file to a REST API, first follow that endpoint’s contract: use its documented HTTP method and URL, authenticate as required, send the accepted content type (often multipart/form-data or a raw binary body), provide the required field names and metadata, and respect its MIME-type and size limits. Some APIs return a completed file resource; others return an upload token or a processing state that requires another request.
There is no universal REST upload format. The examples below show the main patterns, runnable clients, provider-specific size guidance, resumable transfers, asynchronous processing, and the errors that most often break uploads.
Start with the endpoint contract
Before writing code, record these values from the API reference:
- Method and URL: usually
POSTfor a new upload, but some resumable sessions usePUTfor subsequent chunks. - Authentication: API key, bearer token, OAuth access token, signed request, or another scheme.
- Request media type:
multipart/form-data,multipart/related,application/octet-stream, or a provider-specific resumable protocol. - File field and metadata names: for example,
file,media, or a JSON metadata part. - Accepted MIME types and maximum size: validate before transmission.
- Response contract: a file resource, an upload token for a later call, a session URL, or an asynchronous processing status.
Do not infer these values from another service. A request that works with Cloudflare Images may be invalid for Google Drive, even though both accept image files.
#1 Best Overall
- USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
- Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
- Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
- Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
- Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
Choose the request shape
Raw binary body
Use a raw body when the endpoint explicitly documents it. Google Photos’ binary upload step uses application/octet-stream; the bytes are the complete request body and the media type is declared with X-Goog-Upload-Content-Type. The upload returns a token, which is then supplied to a separate media-creation request. Do not wrap this request in a multipart form unless that API says to.
Multipart form data
multipart/form-data packages one or more boundary-separated parts. A file part normally includes Content-Disposition with a field name and filename, plus a part-level Content-Type. Text fields such as a title or folder ID can accompany the file. Let your HTTP library generate the boundary and top-level Content-Type; manually setting a boundary that does not match the body causes parsing failures.
OpenAPI Specification 3.0.2 states: “To upload multiple files, a multipart media type MUST be used.” The exact field names and whether multiple values are allowed still come from the endpoint definition.
Multipart related
multipart/related is different from form data. Google Drive’s metadata-plus-file request puts a JSON metadata part first and the media part second, each with its own content type. Gmail documents the same arrangement. Use it only when the API requires related parts; changing it to multipart/form-data can make an otherwise valid payload unreadable.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Resumable or chunked upload
A resumable protocol starts a session, receives a session URL or identifier, and then accepts one or more content requests. Google Drive recommends resumable uploads for files greater than 5 MB or when an interruption is likely; after the session starts, content requests use PUT. Google Photos also supports splitting media into sections. These thresholds and verbs are provider-specific, not HTTP-wide rules.
Basic multipart upload
When an endpoint accepts a file field, this cURL pattern is the smallest useful starting point. Replace the URL, token, field name, and MIME type with the values in that API’s documentation.
Rank #2
- 2 in 1: USB C + USB 3.0, 32GB usb c flash drive has dual ports, usb 3.0 port is applied to all devices which have usb 3.0 interface and usb c port is widely used in all Android smartphones with OTG function
- High Speed USB 3.0: Read speed up to 90 MB/s, Write speed up to 30 MB/s, the speed of USB 3.0 interface is faster than USB 2.0, save time to wait, increases work productivity. Note: Speed will be limited if you use the USB key in the USB 2.0 interface
- Large Compatibility: The USB 3.0 Connector is compatible with USB 3.0 & USB 2.0 backward USB 1.1 devices, such as Laptop, Desktop, Car Audio, Tablet, TV, Speakers, Projector. USB-C port is compatible with all Android Smartphones
- Expand Storage: Good performance in storing, transferring and sharing digital data with families, friends, colleagues, customers. It can expand the capacity of smartphone, you can watch movies or share pictures when you go on vacation with your family
- Note: Make sure your smartphone is equipped with OTG function and need to open OTG function in Settings when you plug memory stick, then you can transfer easily data bewteen different devices
curl -X POST "https://api.example.com/v1/media"
-H "Authorization: Bearer $TOKEN"
-F "file=@./photo.jpg;type=image/jpeg"
-F "title=Product photo"
The server may return 201 Created with a media object, 202 Accepted while it processes the file, or an error body describing a rejected type, size, or field. Always inspect both the status code and response body.
Python with requests
import mimetypes
from pathlib import Path
import requests
endpoint = "https://api.example.com/v1/media"
token = "YOUR_TOKEN"
path = Path("photo.jpg")
mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
with path.open("rb") as stream:
response = requests.post(
endpoint,
headers={"Authorization": f"Bearer {token}"},
files={"file": (path.name, stream, mime)},
data={"title": "Product photo"},
timeout=(10, 120),
)
response.raise_for_status()
print(response.json())
The files argument creates the multipart boundaries and file headers. The connect/read timeout is only an example; choose values appropriate for the service and file size.
Node.js with fetch and FormData
import { createReadStream } from 'node:fs';
import { basename } from 'node:path';
import { FormData } from 'undici';
const form = new FormData();
form.append('file', createReadStream('./photo.jpg'), {
filename: basename('./photo.jpg'),
contentType: 'image/jpeg'
});
form.append('title', 'Product photo');
const response = await fetch('https://api.example.com/v1/media', {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.API_TOKEN}` },
body: form
});
if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
console.log(await response.json());
Do not set a fixed Content-Type header in this example. The runtime must add the boundary generated for the form.
Raw binary upload example
For an endpoint that specifies a binary body, stream the file directly and send the documented headers. A generic cURL shape is:
curl -X POST "https://api.example.com/v1/upload"
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/octet-stream"
-H "X-Upload-Content-Type: image/png"
--data-binary "@./image.png"
Some services require a separate JSON request after this step. Google Photos, for example, returns an upload token that must be used in a later media-creation call. Treat that token as temporary state and persist it until the second request succeeds.
Metadata plus media with multipart/related
When the API requires metadata and bytes in one request, construct two parts in the documented order. Google Drive’s pattern is metadata first and media second:
Rank #3
- USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
- Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
- Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
- Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
- Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
curl -X POST "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"
-H "Authorization: Bearer $TOKEN"
-H "Content-Type: multipart/related; boundary=BOUNDARY"
--data-binary $'--BOUNDARYrnContent-Type: application/json; charset=UTF-8rnrn{"name":"photo.jpg"}rn--BOUNDARYrnContent-Type: image/jpegrnrn'"$(cat photo.jpg)"$'rn--BOUNDARY--rn'
In production, prefer the provider’s SDK or a multipart builder rather than assembling binary boundaries in a shell. The example illustrates the contract, not a universal Drive configuration; authentication scopes, parent folders, and current API parameters must match the deployed Drive version.
When to use resumable uploads
- Start a session. Send the provider’s initiation request with the file’s type, length if required, and metadata.
- Save the session URL or ID. Treat it as a credential: do not expose it in logs or client-side pages unless the service says it is safe.
- Send chunks. Use the exact chunk size, byte-range headers, and method documented by the provider. Google Drive uses
PUTfor content requests after initiation. - Retry safely. On a timeout or dropped connection, query the session’s received range before retransmitting. Use bounded exponential backoff for transient 5xx and connection errors.
- Finalize and verify. The final response should identify the stored object or processing state. Check the returned size, MIME type, checksum, or media ID when available.
Resuming is valuable when files are large or links are unreliable, but it adds session expiration, chunk accounting, and retry logic. Use a simple upload for a small file when the endpoint and network are dependable.
Provider limits are examples, not defaults
| Service and operation | Published guidance | What it means |
|---|---|---|
| Google Drive simple or multipart upload | 5 MB or less | Simple media is for a file of 5 MB or less without metadata; multipart is for a small file of 5 MB or less with metadata. Drive recommends resumable transfer above 5 MB or when interruption risk is high. |
| Cloudflare Images multipart POST | Up to 10 MB | A single multipart/form-data POST can upload images up to 10 MB, authenticated with an API token. |
| Google Photos media upload | Below 50 MB suggested | The guide suggests staying below 50 MB because larger images are prone to performance issues and supports resumable upload. |
These figures come from the respective provider guides (publication year not stated there). They are not universal REST limits. Check the current endpoint reference immediately before deployment.
Authentication, validation, and safety
- Keep API keys and bearer tokens in environment variables or a secret manager, never in a repository or browser bundle.
- Validate extension, detected MIME type, byte size, and (where possible) image dimensions before upload. An extension alone is not proof of content.
- Use HTTPS and avoid logging raw multipart bodies, authorization headers, or signed upload URLs.
- Apply server-side limits even if the provider has a larger allowance. Decode images in a sandbox if your application will transform them.
- For user-supplied filenames, store a generated identifier and retain the original name only as metadata.
- Use idempotency keys when the API supports them, so a retry does not create duplicate media.
Asynchronous processing and response handling
Upload completion does not always mean the media is ready. Mastodon documents an upload endpoint where large media is processed asynchronously; response behavior differs between smaller images and larger media types, and the correct behavior depends on the API version you target. A 202, a processing flag, or a media ID that is temporarily unavailable should lead to polling or a webhook flow, not an immediate assumption that derivatives are ready.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Implement a state machine such as uploading → processing → ready (or failed). Poll at increasing intervals, stop at a deadline, and surface the provider’s error message. Do not poll indefinitely or treat every non-200 response as retryable.
Troubleshooting common failures
400 or 415: invalid request or media type
Check the top-level content type, each part’s content type, required field names, JSON syntax, and whether the endpoint expects raw bytes instead of multipart. A JPEG sent as application/octet-stream may be correct for one binary endpoint and rejected by another.
Rank #4
- 2-in-1 Dual Design: Features both USB-C and USB-A connectors, making it compatible with phones, tablets, MacBooks, PCs, and laptops-no adapter needed
- Wide Compatibility: Works seamlessly with USB A and USB C devices, ensuring reliable file transfers across smartphones, computers, and more
- Ample Storage Options: Available in 16GB/32GB/64GB/128GB providing plenty of space for photos, videos, music, and documents
- Portable & Lightweight: Compact and durable design for travel, school, or daily use-take your files anywhere
- Plug-and-Play Convenience: No software or drivers required; simply insert into USB-C or USB-A ports and start transferring files instantly
401 or 403: authentication or permission
Confirm the token is present, unexpired, scoped for uploads, and sent in the exact header format. For cloud storage, verify the destination folder or album permission as well as the upload scope.
413: payload too large
Measure bytes before sending and compare them with the endpoint’s limit. Resize or recompress only when your product permits it; otherwise choose the provider’s resumable method or a service with an appropriate limit.
422: valid syntax, unacceptable data
Read the field-level error. Typical causes are a disallowed MIME type, missing metadata, an invalid filename, or dimensions outside a service rule.
Timeouts and connection resets
Use streaming rather than loading an entire file into memory, set explicit connect and read timeouts, and retry only transient failures. For large or interruption-prone transfers, use the provider’s resumable session and verify the received range before retrying.
“Boundary not found”
Your body’s multipart boundary does not match the header. Remove the manually supplied Content-Type and let the client library generate it.
Upload succeeds but the file is missing
Inspect the response for an intermediate token or asynchronous status. Complete the required second request, poll the media resource, or follow the documented webhook before declaring success.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteBest Value
- USB-C STORAGE ON THE GO: This sleek drive is supported by Samsung NAND flash and is incredibly compact to fit in the palm of your hand; Count on reliable performance and fast transfer speeds while staying compact
- PERFORMANCE WITH SPEED: No need to choose between performance and reliability; Experience a fast, powerful flash drive that transfers 4GB files in just 11 seconds with up to 400MB/s USB 3.2 Gen 1 read speeds and is backward compatible with USB 3.0/2.0
- MODERN MEETS ICONIC: The ultra-sleek USB-C drive looks as good as it performs; Featuring a reversible plug, the Type-C inserts into your devices seamlessly every time; Transfer large files with style and ease
- ALWAYS CONNECTED: USB-C is compatible across devices, including laptops, tablets, phones and cameras, with enough space for 63,730 photos or maximum 12 hours of 4K video; With up to 256GB of storage space, this pocket-sized thumb drive comes in handy wherever you go
- TOUGH & TRUSTED: Files stay secure, no matter the terrain; Samsung's flash memory technology makes the Type-C a trustworthy drive to store your valuable data; It's waterproof, shock-proof, magnet-proof, temperature-proof, and X-ray-proof body, plus it's backed by a 5-year limited warranty
Performance and reliability checklist
- Stream files and cap concurrent uploads to protect memory and bandwidth.
- Compute size and, if supported, a checksum before transmission.
- Use connection pooling for batches and backoff with jitter for transient failures.
- Record request ID, media ID, status, elapsed time, and billed or quota-relevant information without recording secrets or file contents.
- Test expired credentials, wrong MIME types, maximum-size files, truncated connections, duplicate retries, and provider-side processing delays.
Or skip the browser setup
If the “media” you need is a rendered webpage rather than a local upload, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—work with Claude, Cursor, and other MCP clients.
cURL (full options are in the ScreenshotNeo documentation):
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Every plan includes its 63 capture options, including full-page and element shots, device and retina settings, PDF controls, custom CSS and JavaScript, waits, request blocking, headers and cookies, geolocation, resizing, caching, signed links, async webhooks, bulk capture of up to 100 URLs per call, and a usage API. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up free for ScreenshotNeo.
Frequently Asked Questions
Should I base64-encode an image before sending it?
Only if the endpoint explicitly defines a base64 field or JSON payload. Multipart and raw-binary endpoints normally expect bytes; base64 adds size and decoding overhead.
Free tools Windows power users keep installed
One-click scans. No signup required.
Can I send several files in one request?
Only when the API defines a multipart request with repeated file fields or an array-style field. Confirm the exact field syntax and per-request count in its schema.
What status code means an upload worked?
The provider decides. 201 commonly means a resource was created, 202 commonly means accepted for processing, and 200 may indicate a completed operation. Validate the response body and any follow-up state.
How should clients handle a user cancelling an upload?
Abort the HTTP stream, cancel or delete the resumable session if the provider supports that operation, and remove any temporary local or server-side file.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →

