download a text file from a website to my local filesystem? #2759
-
SummaryI'd like to serve a simple html page (from axum), that has a button that when I click on it, it lets me download a text file to my local filesystem. The file would be hosted alongside axum, in the local filesystem of wherever axum is being hosted out of. I'm using maud and htmx, which so far is working for what I need it to do. html!(button hx-get="/download" {"download"}), So I need to create a route, that when it gets called, sends a response that is the text file. I tried using ServeDir, but that's for the browser to serve the text file. I'd like the user to be able to download the file and show up in the local filesystem. Is there an example for this? The other option is to upload it to S3 and return the url to the user but if I can do it more simply that would be great. Thanks axum version7.5 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
For reference, since some of the types changed. This is the maud snippet; html!(a href="/download" download { button { "Download" }}) Include this in your router, which is what htmx calls when you click the button; .route("/download", get(download)) This is the function with the new types; async fn download() -> impl IntoResponse {
let file = match tokio::fs::File::open("download_file.txt").await {
Ok(file) => file,
Err(err) => return Err((StatusCode::NOT_FOUND, format!("File not found: {}", err))),
};
let stream = ReaderStream::new(file);
let body = Body::from_stream(stream);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
"text/plain; charset=utf-8".parse().unwrap(),
);
headers.insert(
header::CONTENT_DISPOSITION,
"attachment; filename=\"download_file.txt\"".parse().unwrap(),
);
Ok((headers, body))
} |
Beta Was this translation helpful? Give feedback.
For reference, since some of the types changed.
This is the maud snippet;
Include this in your router, which is what htmx calls when you click the button;
This is the function with the new types;