gpt4 book ai didi

rust - Actix-Web 在处理文件上传时报告 "App data is not configured"

转载 作者:行者123 更新时间:2023-11-29 08:01:24 28 4
gpt4 key购买 nike

我正在使用 Actix 框架创建一个简单的服务器,并且我已经使用一个简单的 HTML 前端实现了文件上传。

use actix_web::web::Data;
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use std::cell::Cell;

// file upload functions, the same as you can find it under the
// actix web documentation:
// https://github.com/actix/examples/blob/master/multipart/src/main.rs :
mod upload;


fn index() -> HttpResponse {
let html = r#"<html>
<head><title>Upload Test</title></head>
<body>
<form target="/" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="Submit"></button>
</form>
</body>
</html>"#;

HttpResponse::Ok().body(html)
}

#[derive(Clone)]
pub struct AppState {
counter: Cell<usize>,
}

impl AppState {
fn new() -> Result<Self, Error> {
// some stuff
Ok(AppState {
counter: Cell::new(0usize),
})
}
}
fn main() {

let app_state = AppState::new().unwrap();

println!("Started http server: http://127.0.0.1:8000");

HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.service(
web::resource("/")
.route(web::get().to(index))
.route(web::post().to_async(upload::upload)),
)
.data(app_state.clone())
})
.bind("127.0.0.1:8000")
.unwrap()
.run()
.unwrap();
}

运行服务器工作正常,但是当我提交文件上传时,它说:

App data is not configured, to configure use App::data()

我不知道该怎么办。

最佳答案

请rust-jp社区的人告诉你正确答案。

使用 Arc 外部 HttpServer

/*
~~~Cargo.toml
[package]
name = "actix-data-example"
version = "0.1.0"
authors = ["ncaq <ncaq@ncaq.net>"]
edition = "2018"

[dependencies]
actix-web = "1.0.0-rc"
env_logger = "0.6.0"
~~~
*/

use actix_web::*;
use std::sync::*;

fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=trace");
env_logger::init();

let data = Arc::new(Mutex::new(ActixData::default()));
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.data(data.clone())
.service(web::resource("/index/").route(web::get().to(index)))
.service(web::resource("/create/").route(web::get().to(create)))
})
.bind("0.0.0.0:3000")?
.run()
}

fn index(actix_data: web::Data<Arc<Mutex<ActixData>>>) -> HttpResponse {
println!("actix_data: {:?}", actix_data);
HttpResponse::Ok().body(format!("{:?}", actix_data))
}

fn create(actix_data: web::Data<Arc<Mutex<ActixData>>>) -> HttpResponse {
println!("actix_data: {:?}", actix_data);
actix_data.lock().unwrap().counter += 1;
HttpResponse::Ok().body(format!("{:?}", actix_data))
}

/// actix-webが保持する状態
#[derive(Debug, Default)]
struct ActixData {
counter: usize,
}

此帖子向上游报告。 Official document data cause App data is not configured, to configure use App::data() · Issue #874 · actix/actix-web

关于rust - Actix-Web 在处理文件上传时报告 "App data is not configured",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56117273/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com