web - 如何在 actix-web 中定义 URL 参数?

标签 web rust actix-web

在 NodeJS 中,路由可以这样定义:

app.get('/:x', (req, res) => {
  console.log(req.params.x)
  res.sendStatus(200)
});

是否有与 actix-web 等效的方法或更好的推荐方法?

我想上传带有 id 标识符的文件,例如 img.save(format!("{}.png", id));可以写。

我当前的代码:

use actix_multipart::Multipart;
use actix_web::{web, App, HttpServer, Responder};
use futures_util::{StreamExt, TryStreamExt};
use serde::Deserialize;
use image::ImageFormat;

async fn get() -> impl Responder {
    web::HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        .body(include_str!("../page.html"))
}

async fn post(mut payload: Multipart) -> impl Responder {
    if let Ok(Some(mut field)) = payload.try_next().await {
        println!("field: {:.?}", field);

        let content_type = field.content_disposition();
        println!("content_type: {:.?}", content_type);

        if let Some(filename) = content_type.unwrap().get_filename() {
            println!("filename: {:.?}", filename);
        }

        let mut full_vec: Vec<u8> = Vec::new();
        while let Some(Ok(chunk)) = field.next().await {
            full_vec.append(&mut chunk.to_vec());
        }
        println!("full_vec: {}", full_vec.len());

        let img = image::load_from_memory_with_format(&full_vec, ImageFormat::Png)
            .expect("Image load error");
        img.save("img.png");
    }
    web::HttpResponse::Ok().finish()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    println!("Started.");

    // Starts server
    HttpServer::new(move || {
        App::new()
            // Routes
            .route("/", web::get().to(get))
            .route("/", web::post().to(post))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

HTML 将被模板化以在表单操作中包含 ID(在更一般的用例中,它们可能是具有不同 ID 的多个表单)。

<!DOCTYPE html>
<html>
  <body>
    <!-- <form id="form" action="/<% id %>" method="post"> -->
    <form id="form" action="/" method="post">
      <input type="file" name="file" required><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

最佳答案

使用https://actix.rs/docs/extractors/ .

更改:

  1. async fn post(mut payload: Multipart)async fn post(path: web::Path<String>, mut payload: Multipart)
  2. .route("/", web::post().to(post)).route("/{id}", web::post().to(post))
  3. <form id="form" action="/" method="post"><form id="form" action="/someTestId" method="post">

关于web - 如何在 actix-web 中定义 URL 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66871139/

相关文章:

php - 在 php mysql 中插入数据失败

javascript - Cookie 并不总是保存 > 触发基于 cookie 的功能

rust - 闭包需要对 lambda 函数的唯一访问

linux - 错误 "/lib/x86_64-linux-gnu/libc.so.6: version ` GLIBC_2.3 3' not found"

rust - 如何高效地使用 Actix Multipart 将单个文件上传到磁盘?

rust - Actix CORS。从浏览器发送请求时出现问题

html - 是否可以在悬停 <p> 标签时显示 div

javascript - 禁止更新连接到 redux 状态的子组件

memory-management - 我是否正确地使用了继承、借用的指针和显式生命周期注解?

linux - 为什么 `change_protection` 在将大量数据加载到 RAM 中时会占用 CPU?