Home > Back-end >  How to add an object or key value pair to MultipartFormDataContent then send it and receive it on th
How to add an object or key value pair to MultipartFormDataContent then send it and receive it on th

Time:04-08

I am sending an image to the API using MultipartFormDataContent and i can grab the image using var file = HttpContext.Request.Form.Files; without a problem. How can I send additional data like an array or object together with the image and then grab it on the other end of the API? I tried using Key value pairs but with no luck getting it on the API. Below is how i am adding using key value pair but i have no idea how i can receive this data on the API:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    using (var content = new MultipartFormDataContent())
    {
        var fileStream = new FileStream(tempFilePath, FileMode.Open);
        formData.Add(new StreamContent(fileStream), fileName, fileName);
        //Below am sending the name from the object lblobj and giving it a key of name
        formData.Add(new StringContent(lblobj.Name), "name");
        streams.Add(fileStream);

        var request = new HttpRequestMessage(HttpMethod.Post, new Uri(_configuration["Application:ApiEndPoint"])   "api/Label/Create")
        {
            Content = formData,
        };

        request.Headers.Add("accept", "application/json");

        var response = await client.SendAsync(request);
        streams.ForEach(stream =>
        {
            stream.Dispose();
        });

        if (response.IsSuccessStatusCode)
        {
            //Handle success
        }
        //handle failure

    }
}

Below is how i receive the file on the API:

 var image = HttpContext.Request.Form.Files;
//Deal with the image(iformfile)

How can i receive the additional data above?

CodePudding user response:

Here's my test result:

enter image description here

using Microsoft.AspNetCore.Hosting;

private readonly IHostingEnvironment _hostingEnvironment;

public HomeController( IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
}

[HttpPost]
public async Task receiveDataAsync(ApiModel model) {
    var name = model.fileName;
    var file = model.image;
    if (file != null)
    {
        string uploadsPath = Path.Combine(_hostingEnvironment.WebRootPath, "css");
        string uniqueName = Guid.NewGuid().ToString()   "_"   name ".png";
        string filePath = Path.Combine(uploadsPath, uniqueName);
        using (Stream fileStream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(fileStream);
        }
    }
}

And this is the model, and I also think you need to create a model for your api:

using Microsoft.AspNetCore.Http;

namespace WebMvcApp.Models
{
    public class ApiModel
    {
        public string fileName { get; set; }
        public IFormFile image { get; set; }
    }
}

CodePudding user response:

I appended the strings from my object in key value pairs like below

   formData.Add(new StringContent(lblobj.PageColor), "pageColor");
   formData.Add(new StringContent(lblobj.Name), "name");                       
   formData.Add(new StringContent(lblobj.SidebarColor), "sidebarColor");
   formData.Add(new StringContent(lblobj.SidebarLinkColor), "sidebarLinkColor");

On the API end point all i did was append these to a model containing all those keys like below;

 public IActionResult Create([FromForm] Label labelobj)
{

//Do something with the values }

The labelobj contains pageColor etc

  • Related