要使用 Rust 的 reqwest
和 actix
库实现文件下载接口,可以按照以下流程进行:
- 首先,在你的
Cargo.toml
文件中添加依赖项:
[dependencies]
actix-web = "3.0"
reqwest = "0.11"
- 创建一个基于
actix-web
的 HTTP 服务器,并设置路由处理函数:
use actix_web::{get, web, App, HttpResponse, HttpServer};
use std::fs::File;
use std::io::Read;
#[get("/download/{filename}")]
async fn download_file(web::Path(filename): web::Path<String>) -> actix_web::Result<HttpResponse> {
// 检查文件路径和权限等逻辑
// ...
// 打开要下载的文件
let mut file = File::open(&filename)?;
// 创建一个向客户端发送数据的流
let mut body = Vec::new();
file.read_to_end(&mut body)?;
// 设置响应头
let content_disposition = format!("attachment; filename={}", filename);
let response = HttpResponse::Ok()
.header("Content-Type", "application/octet-stream")
.header("Content-Disposition", content_disposition)
.body(body);
Ok(response)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(download_file)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
- 运行服务器:
$ cargo run
现在你可以通过访问 http://127.0.0.1:8080/download/filename
来下载文件。其中 filename
是你要下载的文件名。
需要注意的是,上述代码只是一个简单示例,你可能需要根据实际需求进行更多的错误处理、身份验证、文件存在性检查等操作。此外,还可以根据需要使用 reqwest
库来实现客户端下载文件的功能。