pub fn direct_upload(
ctx: &Ctx,
prefix: &str,
field: &str,
request: &DirectUploadRequest,
rules: &Rules,
) -> Result<DirectUpload>Expand description
Starts a direct upload: checks what the browser declares against rules and presigns a PUT of a new key under prefix.
Rails’ DirectUploadsController#create. The browser PUTs the file to
DirectUpload::url with DirectUpload::headers (within 10
minutes), then submits DirectUpload::signed_key with its form;
attach_direct_upload checks the stored object and returns its
Attachment. The file never passes through the Worker: no 100 MB
request limit, no Worker memory or CPU. The key is
<prefix>/<22 random characters>; use a prefix of its own (uploads/photos)
so purge_unattached can find abandoned uploads.
Settings as presign_get; the bucket also needs a CORS rule allowing
PUT from the app’s origin (see the file storage guide). Signing costs
no R2 operation; the upload is one class A operation.
§Errors
Error::Invalid(422) onfieldwhen the declared size or type breaksrules.Error::Internal(500) when anR2_*setting is missing.
§Examples
use axum::{Json, extract::State};
use ocre::storage::{self, DirectUpload, DirectUploadRequest, Rules};
use ocre::{ApiResult, Ctx};
const VIDEO: Rules = Rules { max_bytes: 500 * 1024 * 1024, content_types: &["video/mp4"] };
// POST /videos/uploads with {"filename": "a.mp4", "content_type": "video/mp4", "size": 1234}
async fn start(State(ctx): State<Ctx>, Json(request): Json<DirectUploadRequest>) -> ApiResult<Json<DirectUpload>> {
Ok(Json(storage::direct_upload(&ctx, "uploads/videos", "video", &request, &VIDEO)?))
}