chyabrung-cli 0.2.0

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//! File uploads, saved under `storage/public/uploads/` and served at `/storage/...`.

use chyabrung::prelude::*;
use chyabrung::storage::Storage;

/// `POST /api/upload` (logged in, `multipart/form-data` with a file field)
pub async fn store(Auth(_): Auth, State(storage): State<Storage>, mut form: Multipart) -> Result<Json<serde_json::Value>> {
    while let Some(field) = form.next_field().await? {
        if let Some(name) = field.file_name().map(str::to_owned) {
            let ext = std::path::Path::new(&name).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_string();
            let key = format!("uploads/{}.{ext}", chyabrung::auth::random_token(12));
            storage.put(&key, field.bytes().await?).await?;
            return Ok(Json(json!({ "path": key, "url": storage.url(&key) })));
        }
    }
    Err(Error::bad_request("Send a file in a multipart field"))
}