1

enter image description here

As you can see, I am trying to send an image, and a name through a POST command to a local function.

How Can I read both of these parameters in C#?

This is what I have tried but It can only read File Image.

   [FunctionName("Test")]
public static async Task<HttpResponseMessage> 
     Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = 
 null)]HttpRequestMessage req, TraceWriter log)
{
    //Check if the request contains multipart/form-data.
    if (!req.Content.IsMimeMultipartContent())
    {
        return req.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }


  foreach (var stream in contents.Contents)
    {


        try
        {
            var fileBytes = await stream.ReadAsByteArrayAsync();
            var fileinfo = new FileInfo(stream.Headers.ContentDisposition.FileName.Trim('"'));



         //Can Read File image like this.


        }
        catch(Exception e)
        {
            return req.CreateErrorResponse(HttpStatusCode.Conflict, e);
        }
alan samuel
  • 415
  • 6
  • 28

2 Answers2

1

You can use MultipartFormDataStreamProvider

  1. Use FileData property to get the posted files
  2. Use FormData property to get the values of any form data posted based upon the key.

Check this File Upload and Multipart MIME.

Hussein Salman
  • 7,806
  • 15
  • 60
  • 98
  • I have to save the files to App folder using this method. Is there a workaround to do this like using memory stream? – alan samuel Nov 20 '17 at 01:09
1

Is there a workaround to do this like using memory stream?

According to your requirement, I assumed that you could use HttpContentMultipartExtensions.ReadAsMultipartAsync and you would get the MultipartMemoryStreamProvider, then you could leverage the following code for reading your uploaded files:

var multipartMemoryStreamProvider= await req.Content.ReadAsMultipartAsync();
foreach (HttpContent content in multipartMemoryStreamProvider.Contents)
{  
   // for reading the uploaded file
   var filename= content.Headers.ContentDisposition.FileName.Trim('"');
   var stream=await content.ReadAsStreamAsync();          

   //for formdata, you could check whether `content.Headers.ContentDisposition.FileName` is empty
   log.Info($"name={content.Headers.ContentDisposition.Name},value={await content.ReadAsStringAsync()}");
}

Moreover, you could follow this issue about creating your custom MultipartFormDataMemoryStreamProvider based on MultipartMemoryStreamProvider. And this issue about building custom InMemoryMultipartFormDataStreamProvider based on MultipartStreamProvider.

Bruce Chen
  • 18,207
  • 2
  • 21
  • 35