Reputation: 2513
I have this regular C# Azure function:
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log) ...
And I need to upload here file, e.g. image. How can I add here IFormFile
or is there other way to upload file to function?
Upvotes: 3
Views: 2319
Reputation: 1
Hey U must explore multitype/form-data content-type, for the isolated azure functions, and fetch the file and file info manually from there.
C# code for reference:
var contentType = req.Headers.FirstOrDefault(h => h.Key.Equals("Content-Type"))
.Value.FirstOrDefault();
if (contentType == null || !contentType.StartsWith("multipart/form-data"))
{
var badResponse = req.CreateResponse(System.Net.HttpStatusCode.BadRequest);
badResponse.WriteString("Invalid content type. Expecting multipart/form-data.");
return badResponse;
}
var boundary = MediaTypeHeaderValue.Parse(contentType).Parameters
.FirstOrDefault(p => p.Name.Equals("boundary"))?.Value;
var reader = new MultipartReader(boundary, req.Body);
var section = await reader.ReadNextSectionAsync();
if (section != null && section.ContentDisposition != null)
{
var contentDispositionn = section.ContentDisposition;
var contentDisposition = ContentDispositionHeaderValue.Parse(section.ContentDisposition);
var fileName = contentDisposition.FileName?.Trim('"');
var fileType = section.ContentType;
byte[] fileContent;
if (!string.IsNullOrEmpty(fileName))
{
var fileStream = section.Body;
using (var memoryStream = new MemoryStream())
{
await fileStream.CopyToAsync(memoryStream);
fileContent = memoryStream.ToArray();
}
}
}
Upvotes: 0
Reputation: 15621
To upload a file to an Azure Function, have a look at the Form of the incoming HttpRequest
.
This works for me:
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "files")] HttpRequest req,
ILogger log)
{
foreach(var file in req.Form.Files)
{
using (var ms = new MemoryStream())
{
var file = req.Form.Files[0];
await file.CopyToAsync(ms);
ms.Seek(0, SeekOrigin.Begin);
// Do something with the file
}
}
return new OkResult();
}
Upvotes: 4