Display image in Actix-web

How can I display ina images in actix-web?

This is how I'm trying

#[get("/showimg")]
async fn show_img() -> Result<HttpResponse> {
    let img = std::path::PathBuf::from(
        "./files/product/813310a0-46d1-473a-9355-e89e936d3dcd.jpg",
    );

      Ok(HttpResponse::Ok()
        .content_type("image/jpeg")
        .respose(img) <- pseudocodigo
        ;
}

I have looked for information and I have not found

You could read the image with std::fs::read(path) and set that using body(). However, it's better to use actix's built-in support for static files like images:

https://actix.rs/docs/static-files/

You should not use std::fs::read in async code because it is blocking. Instead, use the alternative provided by Tokio in tokio::fs::read.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.