0

I'm currently trying to build an endpoint that will return an image (not in in bytes nor b64) to the user based on path but I cannot figure out how to do that with Axum and Rust.

The template of the method should look like that I guess:


#[derive(Deserialize)]
pub struct QueryParams {
    path: String,
}

pub async fn get_image(
    Query(QueryParams { path }): Query<QueryParams>
) -> impl IntoResponse {
}

And I already know the equivalent of what I want in C#

public ActionResult GetImage(string path)
{
    FileExtensionContentTypeProvider fileProvider = new();

    if (path.IsNullOrEmpty())
    {
        return NotFound("Parameter 'path' cannot be null or empty.");
    }
    if (!Directory.Exists(Path.GetDirectoryName(path)))
    {
        return NotFound($"Folder '{Path.GetDirectoryName(path)}' not found.");
    }
    if (!System.IO.File.Exists(path))
    {
        return NotFound($"File '{Path.GetFileName(path)}' not found.");
    }
    if (!fileProvider.TryGetContentType(path, out string? contentType))
    {
        throw new ArgumentException(
                $"Could not determine MIME type of {Path.GetFileName(path)}.");
    }

    return PhysicalFile(path, contentType);
}

I already tried to use the crate image, tower-http with the ServeFile struct but I can't figure out how to make it work properly.

If anyone could provide me some explanation or help it would be greatly appreciated!

MidKnight
  • 75
  • 7
  • 2
    [this discussion](https://github.com/tokio-rs/axum/discussions/608) looks relevant – kmdreko Jun 01 '23 at 16:44
  • I've something now but it seems that in the new axum versions, the `response::Headers` seems like it doesn't exist anymore, any ideas where I can find that? – MidKnight Jun 02 '23 at 15:23

0 Answers0