我正在尝试使用 Angular js 上传一个 excel 文件,将字符串数据发送到 Webapi,然后将其转换为文件。但是,当我尝试在资源管理器中打开此文件时,它说文件已损坏。
HTML:
<div ng-click="chooseDocument()" class="btn btn-primary ">
<span class="glyphicon glyphicon-file"></span> Upload
</div>
<input id="chooseDocument" type="file" class="form-control" style="display: none;" onchange="angular.element(this).scope().addDocument(this)" />
Angular Js:
$scope.chooseDocument = function () {
var dialog = $("#chooseDocument");
dialog.trigger("click");
}
$scope.addDocument = function (dialog) {
var files = dialog.files;
var reader = new FileReader();
function readFile() {
var file = files[0];
reader.onloadend = function () {
uploadExcel(file.name, reader.result);
}
reader.readAsDataURL(file);
}
readFile(0);
}
function uploadExcel(filename, file) {
$http.post(getUrl('api/User/UploadExcel'), { DocumentName: filename, DocumentContent: file }).then(function (response) {
//do something
}, function (errors) {
//do Something
});
};
网络接口(interface):
File.WriteAllBytes(@"c:\MyFile\" + document.DocumentName, Encoding.ASCII.GetBytes(document.DocumentContent));
document.DocumentContent has value "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,UEsDBBQABgAIAAAAIQC82fymuQEAACIIAAATAAgCW0NvbnRlbnRf..."
最佳答案
数据为document.DocumentContent为base64格式。 在 base64**,** 之后用逗号拆分数据,给出了适当的 excel 文件。
WebAPI:
File.WriteAllBytes(path, Convert.FromBase64String(document.DocumentContent.Split((",").ToCharArray())[1]));
关于c# - 使用angular js和WebAPI上传excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32497714/