使用 angular js 和 WebAPI 上传 excel 文件

Upload excel file from using angular js and WebAPI

我正在尝试使用 Angular js 上传一个 excel 文件,将字符串数据发送到 Webapi,然后将其转换为文件。但是当我尝试在资源管理器中打开这个文件时,它说文件已损坏。

HTML:

<div ng-click="chooseDocument()" class="btn btn-primary ">
    <span class="glyphicon glyphicon-file"></span>&nbsp;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
    });

};

WebAPI:

 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]));