保存AngularJS一个Excel文件从API控制器 [英] Save a Excel File From API controller in AngularJS

查看:873
本文介绍了保存AngularJS一个Excel文件从API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的Web API控制器(MVC Asp.net 6)的方法下载文件。所以,在API控制器创建我的文件,我想下载我的文件,已经在Excel格式,angularjs。但是,我不知道该怎么办。

I have tried to download a file from a method of my Web API Controller (Asp.net MVC 6). So, my file is created in a api controller and I want download my file, already in excel format, with angularjs. But, I don't know how to do.

下面是我在我的API控制器方法:(它的工作原理,我已经使用这个方法和类在另一个项目Asp.net没有angularj)

Here is my method in my api controller: (it works, I already use this methods and class in an another project Asp.net without angularj)

#region downloadFile
[Route("Download")]
public ActionResult Download()
{
    string companyName = Context.Session.GetString("companyName") as string;
    string fileDownloadName =  Context.Session.GetString("fileDownloadName") as string;
    string baseFolder = System.IO.Path.Combine("C:\\Temp");
    string folder = System.IO.Path.Combine(baseFolder, companyName);
    TempFile tempFile = new TempFile(folder, fileDownloadName);
    tempFile.FindFileInDirectory();
    return File(tempFile._pathDirectory + "\\"+tempFile._fileName, "Application/" + tempFile._fileExt, tempFile._fileName);

}
#endregion

这个方法返回一个Excel文件。现在,我想下载这个文件,该文件在angularjs发送一个HTTP请求。​​

This method returns an excel file. Now, I would download this file that is send in angularjs with a http request.

我试图从fileSaver.js使用的方法的saveAs。我已经添加了JS在我的项目,但是当我想用它,方法始终是不确定的。

I have tried to use the method saveAs from fileSaver.js. I have added the js in my project but when I want use it, the method is always undefined.

 var requestDownloadFile = 
    $http({ 
        url: '/api/customers/Download'
        , responseType: 'arraybuffer'
        , headers: { 
            'contentType': 'application/json'
            , 'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        } 
    });
    requestDownloadFile.success(function (data) {
        saveAs(data, 'test.xlsx');
});

我想在我的成功方法也使用这样的:

I tried to use this too in my success method:

   var blob = new Blob([data], { type: "application/vnd.openxmlformats-      officedocument.spreadsheetml.sheet" })
   var objectUrl = URL.createObjectURL(blob);
   window.open(objectUrl);

它运行下载的文件,但该文件已损坏。

It run a download file, but the file is corrupted.

所以,因为我已经创造了一个API文件,我试图恢复的arrayBuffer但我挡住,所以我尝试它不是真的有效。

So it's not realy effective because I have created a file in API and I have tried to recover an arrayBuffer but I'm blocked so I try.

所有的支持是值得欢迎的。谢谢

All support is welcome. Thanks

推荐答案

所以,我的生活变得复杂。我不得不这样做的成功的:

So, I complicated life. I just had to do this in the success:

  window.open('/api/customers/Download', '_blank', '');
  window.open('link/to/method/api', '_blank', '');

这篇关于保存AngularJS一个Excel文件从API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆