In this post, let's see how we can POST multipart/form-data with files and fields using a HTTP action in a Consumption Azure Logic
App.
I have the following Test API which I am going to call from the Logic App.
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.UseHttpsRedirection();
app.MapPost("/api/Files", async (IFormCollection formCollection) =>
{
IFormFile? file = formCollection.Files.SingleOrDefault();
if (file == null || file.Length == 0)
{
return Results.BadRequest("No file uploaded.");
}
string fileName = file.FileName;
// Save file and ensure file is good
string filePath = Path.Combine(@"<some-location>", fileName);
using FileStream stream = File.Create(filePath);
await file.CopyToAsync(stream);
return Results.Ok(new
{
fileName,
fileSize = file.Length,
someField = formCollection["someField"].ToString()
});
})
.DisableAntiforgery();
app.Run();
In my Logic App, I have a variable called file of type object and it's populated with data.
{"fileName": "<OMITTED>", // some-file.pdf"base64Content": "<OMITTED>", // Base 64 encoded content"contentType": "<OMITTED>" // application/pdf}
{"$content-type": "multipart/form-data","$multipart": [{"headers": {"Content-Disposition": "form-data; name=\"file\"; filename=\"@{variables('file')?['fileName']}\""},"body": {"$content": "@{variables('file')?['base64Content']}","$content-type": "@{variables('file')?['contentType']}"}},{"headers": {"Content-Disposition": "form-data; name=\"someField\""},"body": "Hello World!"}]}
And now when the HTTP action is executed, I can see the values are getting
passed correctly.
Hope this helps.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment