pub fn presign_get(
ctx: &Ctx,
attachment: &Attachment,
disposition: Disposition,
expires_in: u64,
) -> Result<String>Expand description
Presigns a GET of an attachment on R2’s S3 API, valid expires_in seconds (at most 7 days).
The browser downloads straight from R2 (https://<account>.r2.cloudflarestorage.com/...),
not through the Worker. R2 answers with the same safe Content-Type
and Content-Disposition as serve (the URL carries
response-content-type and response-content-disposition). Anyone with
the URL can download the file until it expires: authorize before
presigning and keep lifetimes short. serve_redirect answers a
redirect to it.
Reads the R2_ACCOUNT_ID and
R2_BUCKET variables and the
R2_ACCESS_KEY_ID and
R2_SECRET_ACCESS_KEY secrets.
Signing is local: no R2 operation, microseconds of CPU; the download
is one class B operation. In ocre dev the URL points to the real
bucket, not the local simulation.
§Errors
Error::Internal (500) when one of the four
settings is missing (the message names them and how to set them), or
expires_in is 0 or over 7 days.
§Examples
use axum::{Json, extract::{Path, State}};
use ocre::storage::{self, Attachment, Disposition};
use ocre::{Ctx, OptionExt, Result, params};
// GET /api/documents/{id}/download_url: a link valid 5 minutes.
async fn download_url(State(ctx): State<Ctx>, Path(id): Path<i64>) -> Result<Json<String>> {
let sql = "SELECT file_key AS key, file_filename AS filename, file_content_type AS content_type, \
file_size AS size FROM documents WHERE id = ?1 AND file_key IS NOT NULL";
let file: Attachment = ctx.db()?.first(sql, params![id]).await?.or_404()?;
Ok(Json(storage::presign_get(&ctx, &file, Disposition::Download, 300)?))
}