【问题标题】:arrayBuffer AngularJs POST requestarrayBuffer AngularJs POST 请求
【发布时间】:2016-05-31 23:05:06
【问题描述】:

我有一个这样的 POST 请求:

 $scope.myFunction = function (name, id, value) {
      $http.post(/retrievePDFFiles, {
                    name: name,
                    id: id,
                    value: value
                }).success(function(data, headers) {
                    var filename = headers('filename');
                    if(data.byteLength > 250) {
                        var blob = new Blob([data], {type : 'application/pdf;charset=utf-8'});
                        saveAs(blob, filename);
                    } else {
                        console.log("Error");
                    }

                }).error(function(data) {
                   console.log(data);
                });
}

通过此调用,我发送一些参数以将它们保存在我的数据库中的表中,作为响应,我有一个 pdf 流。对服务器的请求它正确返回 200 并且所有参数都已更正,所有内容都保存在 db 中,但 pdf 不起作用。我在控制台中遇到错误:

SyntaxError: Unexpected token %

如果我调试请求,它将进入 .error 函数。我认为问题在于它不承认它需要下载流,而且我不知道,它不起作用。我想只是添加

responseType : 'arraybuffer'

它会在某个地方工作,但我不知道在哪里!我无法触摸参数的结构..有什么想法吗?

编辑:我尝试了这里写的没有结果 How to read binary data in AngularJS in an ArrayBuffer?

【问题讨论】:

  • 不是重复的,我已经试过了,没有成功
  • 您将配置属性作为第三个参数传递? get 和 post 使用不同数量的参数,get 使用配置选项作为第二个参数,而 post 使用它作为第三个参数
  • 不,在邮局电话$http.post(url,data,{responseType:"arraybuffer"})
  • 不,我说将配置选项作为第三个参数添加到您的调用中,$http.post("/retrievePDFFiles",{name:name,id:id},{responseType:"arraybuffer"})

标签: javascript angularjs rest blob


【解决方案1】:

试试这个:

app.factory('apiService', ['$http', function($http){
    return {
        downloadFile: function(url, file) {
            return $http({
                url: url,
                method: 'POST',
                data: file,
                responseType: 'arrayBuffer'
            });
        }
    };
}]);

控制器

$scope.download = function(name, id, value) {
    //form the payload for file download
    var payload = {
        name: name,
        id: id,
        value: value
    };

    //execute service to download
    apiService.downloadFile('/retrievePdfFiles', payload).then(function(response) {
        //download the blob
        var contentType = response.headers()['content-type'] || octetStreamMime;
        var blob = new Blob([response.data], contentType);
    }).catch(function(response){
        //there's been an error
    });
}

【讨论】:

    猜你喜欢
    • 2013-08-16
    • 2017-08-24
    • 1970-01-01
    • 2020-07-06
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多