【问题标题】:Upload excel file from using angular js and WebAPI使用 Angular js 和 WebAPI 上传 excel 文件
【发布时间】:2015-12-06 11:52:29
【问题描述】:

我正在尝试使用 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..."

【问题讨论】:

  • 我并不惊讶,你为什么不直接上传文件,是什么让你认为它是 asci 编码的文本?
  • 尝试使用 content-type =undefined 上传。
  • @BenRobinson 它适用于图像,因此试图使其适用于 excel。上传文件到底是什么意思。
  • @JSJ 哪里可以做到这一点?
  • 在标题属性下。

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


【解决方案1】:

数据是文档。文档内容是 base64 格式。 在base64**之后用逗号分割数据,**给出了适当的excel文件。

WebAPI:

File.WriteAllBytes(path, Convert.FromBase64String(document.DocumentContent.Split((",").ToCharArray())[1]));

【讨论】:

    猜你喜欢
    • 2014-10-26
    • 2014-03-02
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 2017-07-26
    • 2013-12-22
    • 2017-01-24
    • 2017-07-05
    相关资源
    最近更新 更多