From c3e9a0b1eea94e46ad66ab751faf14cf925c4307 Mon Sep 17 00:00:00 2001 From: serxoz Date: Fri, 21 Oct 2022 15:15:03 +0200 Subject: [PATCH] descargando... falta header CONTENT_TYPE --- src/vistas/download.rs | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/vistas/download.rs b/src/vistas/download.rs index b7003b3..d410a03 100644 --- a/src/vistas/download.rs +++ b/src/vistas/download.rs @@ -1,20 +1,21 @@ use axum::{ body::StreamBody, http::{header, StatusCode}, - // http::StatusCode, - // http::{StatusCode, header::{self, HeaderMap, HeaderName}}, response::IntoResponse, }; -// use http::{header, StatusCode}; use tokio_util::io::ReaderStream; +use tokio::fs::read_dir; + +const BASE_PATH: &str = "uploads"; pub async fn get_file( - axum::extract::Path(_hash): axum::extract::Path + axum::extract::Path(hash): axum::extract::Path ) -> impl IntoResponse { // hash.into_response() + let (fpath, fname) = find_file(hash).await; // `File` implements `AsyncRead` - let file = match tokio::fs::File::open("Cargo.toml").await { + let file = match tokio::fs::File::open(fpath).await { Ok(file) => file, Err(err) => return Err((StatusCode::NOT_FOUND, format!("File not found: {}", err))), }; @@ -24,12 +25,26 @@ pub async fn get_file( let body = StreamBody::new(stream); let headers = [ - (header::CONTENT_TYPE, "text/toml; charset=utf-8"), + // (header::CONTENT_TYPE, "text/toml; charset=utf-8"), ( header::CONTENT_DISPOSITION, - "attachment; filename=\"Cargo.toml\"", + format!("attachment; filename=\"{}\"", fname), ), ]; Ok((headers, body)) } + +async fn find_file(hash: String) -> (String, String) { + let mut file_path = String::from(""); + let mut file_name = String::from(""); + let pai = &hash[0..1]; //primeiro char + let path = format!("{}/{}/{}", BASE_PATH, pai, hash); + + let mut dir = read_dir(path).await.expect("error atopando directorio"); + while let Some(child) = dir.next_entry().await.expect("error listando") { + file_path = child.path().display().to_string(); + file_name = child.file_name().into_string().unwrap(); + } + (file_path, file_name) +}