Search code examples
c#asp.net-corefile-uploadhttpclientiformfile

How to receive MultipartFormDataContent in API?


Net core application. I have one rest API which will send files to another API.

Below is the logic inside first API to send files to second API.

using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await _tokenService.GetToken());
                    MultipartFormDataContent multipartFormData = new MultipartFormDataContent();
                    string contentJson = JsonConvert.SerializeObject(request);
                    HttpContent data = new StringContent(contentJson, Encoding.UTF8, "application/json");
                    multipartFormData.Add(data, "data");
                    foreach (var file in fileList)
                    {
                        if (file.Length <= 0)
                            continue;
                        var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                        multipartFormData.Add(new StreamContent(file.OpenReadStream())
                        {
                            Headers =
                            {
                        ContentLength = file.Length,
                        ContentType = new MediaTypeHeaderValue(file.ContentType)
                            }
                        }, "File", fileName);
                    }
                    try
                    {
                        var response = await client.PostAsync("https://localhost:44370/apisendfile", multipartFormData);
                    }
                    catch (Exception ex)
                    {
                    }
                }

I have second API as below

 public async Task<ActionResult> SendMail([FromBody] MultipartFormDataContent formDataContent)
        {
        }

When I debug in my first API I receive error

Unsupported Media Type

I am trying all the way to figure it out but could not succeed. Can someone help me to identify this issue. Any help would be appreciated. Thanks


Solution

  • Well, you could try following way,

    Web API Controller:

            [HttpPost]
            public string UploadMultipartFile()
            {
                var file = HttpContext.Current.Request.Files.Count > 0 ?
                    HttpContext.Current.Request.Files[0] : null;
    
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
    
                    var path = Path.Combine(
                        HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
                        fileName
                    );
    
                    file.SaveAs(path);
                }
    
                return file != null ? "/MrPerfectMaltipartFolder/" + file.FileName : null;
            }
    

    Folder Location:

    enter image description here

    Tested on Post Man:

    enter image description here

    Open Folder Location:

    enter image description here

    File Uploaded:

    enter image description here

    For N Type of Multipart Data Upload:

        [HttpPost]
        public object UploadMultipartFileList()
        {
            var uploadedFilesName = new List<string>();
            if (HttpContext.Current.Request.Files.Count > 0)
            {
                int count = 0;
               
                foreach (var item in HttpContext.Current.Request.Files)
                {
    
    
                    var getFile = HttpContext.Current.Request.Files[count];
                    if (getFile != null)
                    {
                        var fileName = Path.GetFileName(getFile.FileName);
    
                        var path = Path.Combine(
                            HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
                            fileName
                        );
    
                        getFile.SaveAs(path);
                    }
                    count++;
                    string file = "/MrPerfectMaltipartFolder/" + getFile.FileName;
                    uploadedFilesName.Add(file);
                }
            }
    
    
    
    
            return uploadedFilesName;
        }
    

    Output:

    enter image description here

    Example Both Data and File:

            [HttpPost]
            public object UploadMultipartFileList()
            {
                HttpRequest multipartRquest = HttpContext.Current.Request;
              
               //General Data Part
                string engineerName = multipartRquest.Form["EngineerName"];
                string engineerEmail = multipartRquest.Form["EngineerEmail"];
    
                //File Upload Part
                var FilesName = new List<string>();
                if (HttpContext.Current.Request.Files.Count > 0)
                {
                    int count = 0;
                   
                    foreach (var item in HttpContext.Current.Request.Files)
                    {
    
    
                        var getFile = HttpContext.Current.Request.Files[count];
                        if (getFile != null)
                        {
                            var fileName = Path.GetFileName(getFile.FileName);
    
                            var path = Path.Combine(
                                HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
                                fileName
                            );
    
                            getFile.SaveAs(path);
                        }
                        count++;
                        string file = "/MrPerfectMaltipartFolder/" + getFile.FileName;
                        FilesName.Add(file);
                    }
                }
    
    
    
    
                return FilesName;
            }
    

    Request Format:

    enter image description here

    Output:

    enter image description here

    Hope it would resolve your problem. Feel free to share if you still encounter any issues.