1

I have an endpoint that needs to accept a file upload and also some other information from the client request. With the following code I can upload the file successfully but can't seem to figure out how to read the other info.

I make a test request from Postman with the following form data:

image -- myimage.jpg -- of type File

email -- a@b.com -- of type Text

The backend code looks like this:

[HttpPost]
public async Task<HttpResponseMessage> SharePhoto()
{   
    try
    {
         var provider = new MultipartMemoryStreamProvider();
         var data  = await Request.Content.ReadAsMultipartAsync(provider);

         // this is how I get the image which I am succesfully passing to EmailService
         var item = (StreamContent)provider.Contents[0];
         using (var stream = new MemoryStream())
         {
             await item.CopyToAsync(stream);
             String emailAddress;
             EmailService.SendSharedPhoto(emailAddress, stream);
             return Request.CreateResponse();
         }               
     }
     catch
     {
        // do stuff
     }
}

In this example I am able to access provider.Contents[1] but can't seem to be able to get the value from it into emailAddress. I'm thinking it may be possible to use the same trick as the await item.CopyToASync(stream) from the image upload, but I'm hoping I can get a simpler solution to that. Any ideas?

Vee6
  • 1,527
  • 3
  • 21
  • 40

2 Answers2

1

I just barely answered a very similar question to this yesterday. See my answer here complete with sample controller code.

Community
  • 1
  • 1
ManOVision
  • 1,853
  • 1
  • 12
  • 14
0

The method I ended up using is:

If the form elements are strings (and it worked for me since the mobiel frontend took responsability for input data) you can do this:

var streamContent = (StreamContent)provider.Contents[1];
var memStream = new MemoryStream();
await streamContent.CopyToAsync(memStream);
var actualString = Encoding.UTF8.GetString(x.ToArray());

If however the field needs to represent a collection of items, like for example the email list: ["a@b.com", "x@c.com"], etc a JavaScriptSerializer can be user, like so:

var streamContent = (StreamContent)provider.Contents[1];
var emailAddresses = await str.ReadAsStringAsync();
var jsSerializer = new JavaScriptSerializer();
var deserializedData = jsSerializer.Deserialize<string[]>(emailAddresses);

Note that this is nowhere near safe, though it is few lines of code and happens to work.

Vee6
  • 1,527
  • 3
  • 21
  • 40