Using xlsxwriter
, I have created an .xlsx file ( fn create_workbook()
) that I want to send to the client using rocket
. Downloading works, but the extension is wrong. Ideally, the file should be deleted after the client has downloaded it.
Creating the file works (it's stored under target/simple1.xlsx
), however, the file that gets downloaded upon visiting http://127.0.0.1:8000
is a .dms
file rather than a .xlsx
file. Apparently, the problem is only the file name (and hence, also the extension): If one changes the extension of the downloaded file to .xlsx
, it is the desired document.
Also, I don't know how to delete the file after it has been downloaded from the server, since the function will be exited right after it has been downloaded. (I'm new to rust and also happy about any code recommendations)
use std::fs;
use std::path;
use rocket::{
response::status::NotFound,
fs::{FileServer,
NamedFile}
};
use xlsxwriter::Workbook;
#[macro_use] extern crate rocket;
// create an xlsx workbook at "target/simple1.xlsx"
fn create_workbook()->Result<Vec<u8>,xlsxwriter::XlsxError>{
let workbook = Workbook::new("target/simple1.xlsx");
let mut sheet1 = workbook.add_worksheet(None)?;
sheet1.write_string(2,1,"Hello, world!",None)?;
workbook.close().expect("workbook can be closed");
let result = fs::read("target/simple1.xlsx").expect("can read file");
Ok(result)
}
#[get("/")]
async fn index() -> NamedFile {
let file = create_workbook().expect("file can be created");
let path_to_file = path::Path::new("target/simple1.xlsx");
let res = NamedFile::open(&path_to_file).await.map_err(|e| NotFound(e.to_string()));
match res {
Ok(file) => file,
Err(error) => panic!("Problem with file {:?}", error),
}
// ideally, the file would be deleted after it has been sent to the client
// fs::remove_file("target/simple1.xlsx").expect("can delete file");
}
#[launch]
fn rocket() -> _ {
let rocket= rocket::build();
rocket
.mount("/", routes![index])
}
The Cargo.toml
file is:
[package]
name = "demo_download_xlsx_rust"
version = "0.1.0"
edition = "2021"
[dependencies]
xlsxwriter = "0.4.0"
[dependencies.rocket]
version = "0.5.0-rc.2"
I followed the Response
guide as closely as possible (doc). I also tried returning a Result<NamedFile, NotFound<String>>
.