0

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

Callum Linington
  • 14,213
  • 12
  • 75
  • 154
jitender
  • 10,238
  • 1
  • 18
  • 44

2 Answers2

1

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;
        }
jitender
  • 10,238
  • 1
  • 18
  • 44
0

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.

Alex
  • 3,689
  • 1
  • 21
  • 32
  • Thanks but i think you didn't got my question i want to post a file to that api from my side for example client.postAsync(filestream as param(import) here) but PostAsync not allow to post the filestream directly .I just wana ask how i can post my filestream to that api from my side. – jitender Jun 21 '16 at 09:19
  • @jitender i think this might help you: http://stackoverflow.com/questions/10339877/asp-net-webapi-how-to-perform-a-multipart-post-with-file-upload-using-webapi-ht – Alex Jun 21 '16 at 09:44
  • Thanks it works for me with a little change stream.Headers.Add("Content-Disposition", "form-data; name=\"import\"; filename=\"attendances.xslx\""); Again thanks – jitender Jun 21 '16 at 12:11