我需要上传 csv 文件并解析它。我可以在 http 正文请求中看到文件,但是当我在 csvreader 中传递它时,我可以看到像标题一样的 base64 字符串:
在客户端,我使用 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 Content-Disposition: form-data; 名称="文件"
data:application/vnd.ms-excel;base64,RW1haWwsRmlyc3ROYW1lLExhc3ROYW1lDQpwcm9zdG8uZHVkYUBnbWFpbC5jb20yLERlbmlzLER1ZGFpZXYNCnByb3N0by5kdWRhQGdtYWlsLmNvbSxEZW5pcyxEdWRhaWV2DQpwcm9zdG8uZHVkYUBnbWFpbC5jb20yLERlbmlzLER1ZGFpZXYNCg==
------WebKitFormBoundarySKPlgJRINOMnpxVP--
更新
@Ubercode 建议我将 base 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();