C#如何上传 csv 文件并将它解析?

发布时间: 2017/2/23 20:08:49
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我需要上传 csv 文件和解析它。 我可以看到文件在身体的 http 请求,但当我穿过它,csvreader 我可以看到像头 base64 字符串︰enter image description here

在客户端上使用 angularjs:

'uploadBulkUsersFile': {
                method: 'POST', url: CONFIG.apiServiceBaseUri + "api/users/bulkUsers",
                headers: {
                     "Content-Type": undefined
                },
                transformRequest: angular.identity,
                withCredentials: true
            },

和电话︰

var _uploadBulkUsersFile = function (bulkUsersFile) {
    var fd = new FormData();
    fd.append("file", bulkUsersFile);

    return usersResource.uploadBulkUsersFile({}, fd, function (result) {
        return result;
    }).$promise;
};

和在服务器端,我使用 webapi2:

    if (!Request.Content.IsMimeMultipartContent())
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
    foreach (var file in provider.Contents)
    {
        var buffer = await file.ReadAsStreamAsync();

        TextReader textReader = new StreamReader(buffer);
        var csv = new CsvReader(textReader);
        var records = csv.GetRecords<BulkUploadUser>().ToList();

        return Created("DefaultApi", records);
    }

http 请求有效负载

---WebKitFormBoundarySKPlgJRINOMnpxVP 内容处置︰ 表单数据;名称 ="文件"

data:application/vnd.ms-excel;base64,RW1haWwsRmlyc3ROYW1lLExhc3ROYW1lDQpwcm9zdG8uZHVkYUBnbWFpbC5jb20yLERlbmlzLER1ZGFpZXYNCnByb3N0by5kdWRhQGdtYWlsLmNvbSxEZW5pcyxEdWRhaWV2DQpwcm9zdG8uZHVkYUBnbWFpbC5jb20yLERlbmlzLER1ZGFpZXYNCg==
------WebKitFormBoundarySKPlgJRINOMnpxVP--

更新

@Ubercode 建议我基地 64 转换字符串,我做到了,但看起来很恶心︰

var buffer = await file.ReadAsStreamAsync();

TextReader textReader = new StreamReader(buffer);
var text = textReader.ReadToEnd();
var indexOfWord = "base64,";
var base64EncodedBytes = System.Convert.FromBase64String(text.Substring(text.IndexOf(indexOfWord) + indexOfWord.Length));
var encoded = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
TextReader textReader2 = new StringReader(encoded);
var csv = new CsvReader(textReader2);
var records = csv.GetRecords<BulkUploadUser>().ToList();

解决方法 1:

你需要到您的文件解码 base64 编码的东西︰

如何进行编码和解码 base 64 字符串

因此你可以整理你一点点的代码︰

string text;
using(TextReader textReader = new StreamReader(buffer))
     text = textReader.ReadToEnd();

CsvReader csv;

using(var ms 
   = new MemoryStream(Convert.FromBase64String(text.Substring(text.IndexOf(',') + 1)))
using (var textReader2 = new StreamReader(ms))
    csv = new CsvReader(textReader2);

var records = csv.GetRecords<BulkUploadUser>().ToList();
官方微信
官方QQ群
31647020