c# - 使用angular js和WebAPI上传excel文件

标签 c# jquery html css asp.net-web-api2

我正在尝试使用 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
    });

};

网络接口(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/

相关文章:

c# - 如何在与 ItemsSource 绑定(bind)的 ListBox 中显示子元素的属性?

c# - 界面无法更新

c# - Visual Studio 不再显示 IntelliSense 描述

javascript - 在运行时在 Javascript 、 jQuery 中为图像标签指定新源

c# - 如何从 wpf 中的文本框聚焦光标?

javascript - 类更改后元素丢失属性

javascript - 元素内容更改的问题 - 我怎样才能获得新值?

javascript - 关闭模态覆盖时无法隐藏消息框

Javascript - 如何使用循环在对象内定义数组?

php - 产品未添加到购物车