How to transfer a collection of pictures from react(axios) to ASP.NET Core server?

23 Views Asked by At

The problem is that I can't write a request to send an array of files to endpoint.

About the server-side: the project server is built on ASP.NET Core (Minimal API).

Endpoint:

public static IEndpointRouteBuilder MapImagesEndpoints(this IEndpointRouteBuilder builder)
{
    builder.MapPost("/images", LoadImages)
        .DisableAntiforgery();
    return builder;
}

private static async Task<IResult> LoadImages(
    HttpContext context,
    IImageService imageService,
    [FromForm] List<IFormFile> images) // The IFromFileCollection variant was also used
{
    try
    {
        return Results.Ok(await imageService.LoadImagesAsync(images));
    }
    catch
    {
        return Results.BadRequest(new ErrorDto("An unexpected error occurred while loading the image."));
    }
}

The project's client side is built using React. Axios is used to send requests to the server.

Request:

const data = new FormData();
images.forEach((image) => {
    data.append("images", image);
});
await Api.UploadImages(data);

static async UploadImages(images: FormData): Promise<AxiosResponse> {
    return axiosApi.post(
        "/images/images", // This is the correct path, don't mind that it doesn't match what is     written in MapImagesEndpoints().
        images,
        {
            headers: {
                "Content-Type": "multipart/form-data",
        },
    });
}

I tried changing List<IFromFile> to IFromFileCollection, but I still don't understand how to write the query correctly.

In all cases I got an error on the server side that the request cannot be read.

0

There are 0 best solutions below