从asp.net mvc下载带blob的文件

时间:2018-03-30 08:36:04

标签: javascript angularjs asp.net-mvc

我想使用blob从我的角度控制器下载一个excel。

mvc应用程序的服务器代码是

    [HttpGet]    
    public HttpResponseMessage Download(SearchModel search){
        string fileName = "test.xls"

        byte[] file = GetFile(search)
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)

        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();                    
        httpResponseMessage.Content = new ByteArrayContent(file.ToArray());                    
        httpResponseMessage.Content.Headers.Add("x-filename", fileName);                    
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");                    
        httpResponseMessage.Content.Headers.ContentDisposition = new    ContentDispositionHeaderValue("attachment");                    
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;                    

        return httpResponseMessage;   
    }    

和js

$http({ method: 'GET', url: 'Download', params: {...some params}, responseType: 'arrayBuffer' })
    .success(function (data, status, headers) {

        headers = headers();
        var filename = headers['x-filename'];
        var contentType = headers['content-type'];
        var linkElement = document.createElement('a');
        try {
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(new Blob([data],{type: "application/octet-stream"}));
                return;
            }

            var a = $("<a style='display: none;'/>");
            var url = window.URL.createObjectURL(new Blob([data], {type: "application/octet-stream"}));
            a.attr("href", url);
            a.attr("download", "name");
            $("body").append(a);
            a[0].click();
            window.URL.revokeObjectURL(url);
            a.remove();
        }
        catch (ex) {
            console.log(ex);
        }
    })
    .error(function () {  });     

但有一些问题:

  1. javascript端的文件名未定义,而不是服务器端的test.xls
  2. contentType是&#34; text / html;字符集= UTF-8&#34;而不是&#34; application / octet-stream&#34;在服务器端
  3. 下载的文件是
  4. StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content:  System.Net.Http.ByteArrayContent, Headers:
    {
      x-filename: test.pdf
      Content-Type: application/octet-stream
      Content-Disposition: attachment; filename=test.pdf
    }
    

    该文件是带有标题信息的JSON。 为什么这个文件错了?

0 个答案:

没有答案