用rust的actix_web开发项目,需要提供文档下载功能,
先来了解一下header中Content-Disposition的作用
Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。当 浏览器 接收到头时,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名。详细解释请点击
利用actix_web的帮助文档下面代码能实现下载功能
async fn response_body(req: web::HttpRequest) -> HttpResponse {
println!("request={:?}", req);
let mut builder = HttpResponse::Ok();
let cd1 = ContentDisposition {
disposition: DispositionType::Attachment,
parameters: vec![DispositionParam::FilenameExt(ExtendedValue {
charset: Charset::Iso_8859_1, // The character set for the bytes of the filename
language_tag: None, // The optional language tag (see `language-tag` crate)
value: b"test.csv".to_vec(), // the actual bytes of the filename
})],
};
builder.set_header(actix_web::http::header::CONTENT_DISPOSITION, cd1);
let stream = body::Body::from("this document content");
builder.message_body(stream)
}