C#使用httpclient发布excel文件

时间:2016-06-21 08:21:55

标签: c# file-upload httpclient

我需要读取一个excel文件并将其发布到WebApi端点。端点具有import类型的HttpPostedFileBase参数,如下所示

[AcceptVerbs(HttpVerbs.Post)]

public JsonResult Upload(HttpPostedFileBase import)
{
}

如何使用FileStream HttpClient方法将PostAsync发送到上述方法。

提前致谢

2 个答案:

答案 0 :(得分:0)

根据我的经验,您必须从Request对象获取文件,并且不需要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);
        }
     }
}

我使用OfficeOpenXml来处理Excel,您可以将其作为nuget包使用。

答案 1 :(得分:0)

它对我有用,如下所示

    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;
        }