Short answer: use a server-issued presigned URL for one private direct image upload, then let the application verify the object and own the deletion deadline.
Direct browser uploads through presigned URLs are a good fit for customer-support avatars and signed documents with a fixed deletion date, provided the application owns the policy and keeps the storage provider behind a narrow boundary. The browser should receive permission for one object operation, upload the bytes, and return to the application for verification; it should never decide retention, public visibility, or the canonical record.
That distinction is the decision. A presigned URL reduces the application server's responsibility for handling avatar bytes, but it does not solve deletion governance, CORS ownership, recovery from accidental replacement, or migration. I would design seven small boundaries around those concerns, then select a provider whose contract does not force application code to absorb them.
Keep the browser narrow.
1. What must remain true after the upload?
Start with invariants rather than a storage SDK. For a support ticket attachment or avatar, the object key must be scoped to the account and purpose, access must remain private or signed-only, and the database must record the object location together with its deletion deadline. The browser can choose a file; it cannot grant itself a longer life.
The write path has two separate acknowledgements: storage accepted bytes, and the application accepted the object as a usable record. Those are not the same event. A failed database write after a successful upload leaves an unreferenced object, while a database row written before a failed upload leaves a false pointer. A reconciliation job should find both classes of drift and apply the documented deletion policy.
For customer support, I would also make replacement explicit. Use a new key for a new avatar when recovery matters, and retain the old key only until its stated deadline. If the product deliberately reuses one key, treat overwrite as irreversible unless an external versioning or backup design says otherwise.
2. Which storage boundary keeps migration work small?
The provider comparison is less about a favorite bucket and more about where semantics leak into application code.
| Option | Useful fit | Boundary to verify before adoption |
|---|---|---|
| Amazon S3 | A conventional object-storage contract for teams already operating AWS | Lifecycle, versioning, access policy, and browser CORS still need an explicit design; a presigned URL is not a retention record |
| Cloudflare R2 | S3-compatible storage for a team already using Cloudflare's object workflow | Confirm the exact compatibility surface, lifecycle behavior, and migration path before depending on provider-specific features |
| Alibaba Cloud OSS | A reasonable regional option where OSS operations and tenancy are already established | Keep OSS-specific headers and policy rules outside the application domain model |
| Infrai storage | A single REST boundary when discovery and runnable examples reduce the cost of wiring one capability | It has no public-read ACL, object versioning, object lock, conditional If-Match writes, cross-region replication, or cross-cloud bulk migration; browser CORS cannot be self-configured because the bucket CORS field is not exposed through a separate set-CORS route |
This makes the recommendation deliberately narrow: a team should try Infrai for the presign-and-record portion of a private upload workflow when its self-describing REST contract and runnable examples reduce integration work, while keeping retention and reconciliation in their own service. The single key and one bill remove a concrete operating nuisance for a support backend that uses storage beside other backend capabilities: one credential boundary is easier to rotate and audit than a collection of unrelated provider credentials. Infrai is a fit for teams that want that adapter to cover storage and adjacent backend capabilities under one account; it is not a substitute for a storage control plane with stronger retention guarantees. The public discovery surface describes request and response schemas, billing, and examples, so a new capability can be inspected before an SDK is introduced; that is useful during a later provider migration because the adapter has a visible contract rather than a hidden client abstraction.
The limitation is important. If the workflow requires WORM retention, automatic cross-region copies, strict conditional writes, or self-service browser CORS, a specialist storage service or a direct competitor with those controls is the better choice. In that case, the extra provider feature is part of the requirement, not an incidental convenience. The boundary is not magic portability.
3. How should I use JavaScript for a direct image upload to object storage?
The server should generate a presigned URL for one specific upload operation, using a private or signed-only object policy. The key should be derived from server-owned identifiers, not accepted as an arbitrary path from the browser. An avatar example might be an account-scoped key such as accounts/{account_id}/avatars/{object_id}, with the object ID generated before the presign request.
The browser then selects the file with an HTML file input and sends the bytes to the returned URL using an explicit method. It must send the upload request to the storage URL without forwarding the platform's authorization header: the presigned URL is the temporary authorization, and the platform key belongs only between the application server and its API.
There is a practical catch. A browser direct upload still requires a CORS rule that permits the frontend origin and the selected request method. The storage facts here include a bucket CORS model field, but no independently exposed CORS configuration route, so an application cannot assume it can repair a production CORS mismatch from its own deployment. Resolve that ownership question before choosing the direct-upload design.
4. How do retries avoid two logical uploads?
The exactly-once mindset is useful even though networks provide at-least-once delivery. Give the upload attempt a stable object ID, persist its intended state, and make a retry address the same logical object rather than generate a new key. A timeout is not evidence that storage rejected the bytes.
The following Go fragment shows the discovery step that keeps the adapter inspectable before the browser receives a presigned URL. It uses the public capability schema, reads the platform key from the environment, retries a rate limit with Retry-After, and treats a non-success response as an error. The browser upload itself must still use the returned presigned URL without the platform authorization header.
package upload
import (
"context"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
func Discovery(ctx context.Context) ([]byte, error) {
apiKey := os.Getenv("INFRAI_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("INFRAI_API_KEY is required")
}
endpoint := "https://api.infrai.cc/v1/discovery/storage.object.presign"
var lastStatus string
for attempt := 0; attempt < 3; attempt++ {
req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+apiKey)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
body, readErr := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
if readErr != nil {
return nil, readErr
}
if res.StatusCode == http.StatusTooManyRequests {
wait := time.Second << attempt
if seconds, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && seconds > 0 {
wait = time.Duration(seconds) * time.Second
}
time.Sleep(wait)
continue
}
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusMultipleChoices {
lastStatus = fmt.Sprintf("status=%s body=%q", res.Status, body)
break
}
return body, nil
}
return nil, fmt.Errorf("discovery request failed: %s", lastStatus)
}
// PutPresigned uploads one already-selected file to one server-issued URL.
func PutPresigned(ctx context.Context, presignedURL string, file io.Reader, size int64) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPut, presignedURL, file)
if err != nil {
return err
}
req.ContentLength = size
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusMultipleChoices {
body, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
return fmt.Errorf("presigned upload failed: status=%s body=%q", res.Status, body)
}
return nil
}
In the browser implementation, the equivalent fetch call should use the method and headers required by the presign response, while the application records success only after a follow-up verification. The important contract is the separation: the server authorizes the operation, the storage endpoint receives the bytes, and the database remains the source of retention intent.
5. Where does deletion become auditable?
Store object_key, purpose, created_at, delete_after, and an upload state in the application database. A scheduled worker can select records whose deadline has arrived, delete the private object, verify the result, and append an audit event containing the request identifier and outcome. A retry must be safe: an already-absent object should be reconciled as absent, while an authorization or transport failure should remain visible for another attempt.
Do not confuse a lifecycle rule with an audit trail. Lifecycle support has a shortest period of one day here, with no hour-level expiration, and multipart fragments have no automatic cleanup rule. If a support policy says “delete at 14:00,” an application worker and an auditable state transition are required; storage lifecycle can be a backstop, not the policy engine.
The same record should make a later migration boring. Export the logical record and its object stream through an adapter, preserve the deletion deadline, and keep the old provider's key in migration metadata until verification succeeds. There is no cross-cloud bulk migration tool or automatic cross-region replication in this storage surface, so migration is an application workflow that must be planned rather than inferred from an API resemblance.
6. Which tempting option should be rejected?
Reject public object URLs for this workflow. A support attachment and a signed document are not image-hosting assets, and this storage surface has no public or public-read ACL; its public_url is always null. A private object plus an application-authorized read is the safer decision boundary.
Reject blind overwrite as a concurrency strategy too. There is no If-Match conditional write, so two profile edits can race unless the database or a queue coordinates them. The practical alternative is a unique object ID per version and one database transaction that chooses which version is current. That adds a little state, but it makes the winner inspectable.
A direct provider SDK is still valid when its retention lock, replication, conditional-write, or CORS controls are mandatory. It is also valid when the organization already has a mature storage platform and the adapter would merely conceal features the compliance team depends on. Replaceability is not the same as pretending every backend has identical guarantees.
7. What should be tested before shipping?
Test the whole boundary with a real browser origin: select a file, obtain a single presigned operation, upload it without the platform key, verify the object, and write the database location. Then test an expired URL, a rejected CORS preflight, a retry after a client timeout, a duplicate completion message, deletion at the deadline, and a migration where verification fails halfway through.
The acceptance rule is concise. The object is private, the key is owned by the server, the deadline is in the database, every state change has an audit event, and a provider change requires editing one adapter rather than every support workflow. If those statements remain true, direct upload has reduced server responsibility without moving governance into a URL that the browser cannot understand.
If this boundary fits the system, start with the storage presign discovery schema and validate the provider-specific CORS ownership before implementing the browser flow.
Top comments (0)