简体   繁体   中英

How to read an image and text value in C#?

在此处输入图片说明

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);
        }

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM