使用rust actix下载文件时内容类型错误

xqk2d5yq  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(57)

我想用rust acitx_web下载一个zip文件,这是服务器端代码,看起来像:

pub async fn download_project(
    form: web::Json<DownloadProj>
) -> Result<NamedFile> {
    let trash_result = handle_compress_proj(&form.0);
    return Ok(trash_result.unwrap());
}

字符串
handle_compress_proj将文件夹压缩为zip文件,并将zip文件返回给客户端,这就是handle_compress_proj的样子:

pub fn handle_compress_proj(_req: &DownloadProj) -> Option<NamedFile> {
    let archive_path = gen_zip();
    let file_result = NamedFile::open(archive_path);
    if let Err(err) = file_result {
        error!("read file error,{}", err);
        return None;
    }
    return Some(file_result.unwrap());
}


当我调用这个API时,服务器端告诉错误Content type error。我应该怎么做来修复这个问题?这是所有的actix依赖项:

actix-web = "4"
actix-web-validator = "5.0.1"
actix-rt = "2.9.0"
actix-multipart = "0.6.1"
actix-files = "0.6.2"


我试着这样修改代码:

pub async fn download_project(
    req: HttpRequest,
    form: web::Json<DownloadProj>
) -> impl Responder {
    let path = handle_compress_proj(&form.0);
    match NamedFile::open(&path) {
        Ok(fe) => NamedFile::into_response(fe, &req),
        Err(_) => HttpResponse::BadRequest().json("can't download file")
    }
}


仍然无法解决这个问题。

a0zr77ik

a0zr77ik1#

返回类型应该是actix_web::Result<impl actix_web::Responder>,actix将根据您返回的文件类型添加适当的头。
E.I.

#[actix_web::get("/test-zip")]
async fn test_zip() -> actix_web::Result<impl actix_web::Responder> {

    let path = std::path::PathBuf::from("ZIP_PATH");
    
    if path.exists() {
        let file = actix_files::NamedFile::open(path)?; 
        Ok( file.use_last_modified(true) ) 
    } else {
        Err(actix_web::error::ErrorBadRequest("File not Found") )
    }
}

字符串

相关问题