added file_from_bytes

This commit is contained in:
Philippe Loctaux 2023-02-28 17:24:57 +01:00
parent 95b908836e
commit 27cc4c0956

View file

@ -0,0 +1,29 @@
use rocket::http::ContentType;
use rocket::response::Responder;
use rocket::{response, Request, Response};
use std::io::Cursor;
pub struct FileFromBytes(Vec<u8>);
impl From<&[u8]> for FileFromBytes {
fn from(value: &[u8]) -> Self {
Self(value.to_vec())
}
}
#[rocket::async_trait]
impl<'r> Responder<'r, 'static> for FileFromBytes {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
// Set HTTP ContentType from guessing the file extension
// Serve file as raw bytes if guessing fails or extension is not supported in Rocket
// Thanks Sergio for the code review! <3
let content_type = infer::get(&self.0)
.and_then(|mime| ContentType::from_extension(mime.extension()))
.unwrap_or(ContentType::Bytes);
Response::build()
.header(content_type)
.sized_body(self.0.len(), Cursor::new(self.0))
.ok()
}
}