jitender
jitender

Reputation: 10429

C# Posting excel file using httpclient

I need to read an excel file and post it to a WebApi endpoint. The endpoint has a parameter named import of type HttpPostedFileBase as given below

[AcceptVerbs(HttpVerbs.Post)]

public JsonResult Upload(HttpPostedFileBase import)
{
}

How can I send my FileStream to above method using HttpClient PostAsync method.

Thanks in advance

Upvotes: 0

Views: 5469

Answers (2)

jitender
jitender

Reputation: 10429

It works for me as below

    using (var content = new MultipartFormDataContent())
        {
           var stream = new StreamContent(File.Open(filePath,FileMode.Open));

            stream.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            stream.Headers.Add("Content-Disposition", "form-data; name=\"import\"; filename=\"attendances.xslx\"");
            content.Add(stream, "import", "attendances.xslx");

            var response = client.PostAsync(methodePath, content).Result;
            var result = response.Content.ReadAsAsync<ResponseModel<AttendanceModel>>().Result;
            return result.IsSuccess;
        }

Upvotes: 2

Alex
Alex

Reputation: 3889

From my experience you must get the file from the Request object, and there's no need of HttpPostedFileBase

[HttpPost] 
public ActionResult Upload(WhateverModel model)
{ 
    fileName = file.FileName;  
    var dataList = new List<ExcelDataModel>();
    using (var package = new ExcelPackage(file.InputStream))
    {
        var currentSheet = package.Workbook.Worksheets;
        var workSheet = currentSheet.First();
        var rowCount = workSheet.Dimension.End.Row;

        for (int i = 2; i <= rowCount; i++)
        {
            var dm = new ExcelDataModel
            {
                Value = workSheet.Cells[i, 1].Value.ToString(),
                Name = workSheet.Cells[i, 2].Value.ToString(),
                Label = workSheet.Cells[i, 3].Value.ToString()
            };

            dataList.Add(dm);
        }
     }
}

I used OfficeOpenXml to work with Excel, you can get it as a nuget package.

Upvotes: 0

Related Questions