首页 \ 问答 \ 使用Angular和Django下载文件(Download file with Angular and Django)

使用Angular和Django下载文件(Download file with Angular and Django)

我有一个表,其中包含从服务器获取的文件列表。 我还有一个按钮,可以下载所选文件。 所以我创建了一个调用服务的函数,它在新窗口中打开响应(文件),因此用户可以下载它。 控制器:

  $scope.download = function() {

if ($scope.cancelPromise) {
  $scope.cancelPromise.resolve();
}
$scope.cancelPromise = $q.defer();
UserFileSrv.downloadFile.download(
  {
    fileId: $scope.selectedFile.id
  },function(data) {
    if (data) {
      toaster.pop('success', 'Success', 'success');
      window.open(data);
    }
  }, function(error) {
    if (error) {
      toaster.pop('error', 'Error', error);
    }
  }
);

};

服务:

angular.module('app').factory('UserFileSrv', ['$resource', function($resource) {
var userFile = {
    downloadFile: $resource('my_url/:fileId/?', {
      fileId: '@fileId'
    }, {
      download: {
        method: 'GET',
        isArray: false
      }
    })
    };
    return userFile;
}]);

浏览器显示“成功”烤面包机,但它会打开一个包含此字符串的窗口: Cannot GET /%5Bobject%20Object%5D

注意:响应的Content-Type是: application/json


I have a table containing a list of files fetched from the server. I also have a button, that downloads the selected file. So I made a function which call a service and it opens the response (the file) in a new window, so the user can download it. Controller:

  $scope.download = function() {

if ($scope.cancelPromise) {
  $scope.cancelPromise.resolve();
}
$scope.cancelPromise = $q.defer();
UserFileSrv.downloadFile.download(
  {
    fileId: $scope.selectedFile.id
  },function(data) {
    if (data) {
      toaster.pop('success', 'Success', 'success');
      window.open(data);
    }
  }, function(error) {
    if (error) {
      toaster.pop('error', 'Error', error);
    }
  }
);

};

The service:

angular.module('app').factory('UserFileSrv', ['$resource', function($resource) {
var userFile = {
    downloadFile: $resource('my_url/:fileId/?', {
      fileId: '@fileId'
    }, {
      download: {
        method: 'GET',
        isArray: false
      }
    })
    };
    return userFile;
}]);

The browser shows the 'success' toaster, but it opens a window which contains this string: Cannot GET /%5Bobject%20Object%5D

Note: the Content-Type of the response is: application/json


原文:https://stackoverflow.com/questions/36980166
更新时间:2019-06-21 03:06

最满意答案

您似乎尝试将下载的内容传递给window.open函数。 window.open接受url作为第一个参数。 您可以在两种情况下解决您的问题:

1)形成资源的URL(例如:'my_url / 12343')并将其传递给打开的窗口。 但请确保您的服务器返回带有标题Content-Disposition = attachment; fileName = someFileName的响应 。 它将强制浏览器将响应作为附件进行处理。

2)否则你可以使用Blob。 (它不适用于IE 9或更低版本)

https://developer.mozilla.org/en-US/docs/Web/API/Blob

您可以执行以下操作,而不是使用windows.open:

function downloadBlob(fileName, blob){

  //IE case
  if (!!window.navigator.msSaveBlob){
    window.navigator.msSaveBlob(blob, fileName);
    return;
  }

  //create url
  var url = URL.createObjectURL(blob);

  //create invisible acnhor, to specify the file name
  var a = document.createElement('a');
  document.body.appendChild(a);
  a.style = "display: none";
  a.href = url;
  a.download = fileName;
  a.click();

  setTimeout(function(){
    URL.revokeObjectURL(url);
    document.body.removeChild(a);
  }, 100);

}

var data = {x: 1, y:2, name: 'abc'};
var blob = new Blob([JSON.stringify(data)], {type : 'octet/stream'});

downloadBlob('myData.json', blob)

显示如何使用ngResource下载blob的完整解决方案就在这里


It seems that you try to pass the downloaded content to the window.open function. window.open accept the url as the first argument. You can solve your problem in two cases:

1) Form the url to the resource (ex: 'my_url/12343') and pass it to the window open. But make sure that your server returns your response with header Content-Disposition=attachment;fileName=someFileName. It will force the browser to process the response as an attachment.

2)Otherwise you can use Blob. (it won't work in IE 9 or less)

https://developer.mozilla.org/en-US/docs/Web/API/Blob

Instead of windows.open you can make the following:

function downloadBlob(fileName, blob){

  //IE case
  if (!!window.navigator.msSaveBlob){
    window.navigator.msSaveBlob(blob, fileName);
    return;
  }

  //create url
  var url = URL.createObjectURL(blob);

  //create invisible acnhor, to specify the file name
  var a = document.createElement('a');
  document.body.appendChild(a);
  a.style = "display: none";
  a.href = url;
  a.download = fileName;
  a.click();

  setTimeout(function(){
    URL.revokeObjectURL(url);
    document.body.removeChild(a);
  }, 100);

}

var data = {x: 1, y:2, name: 'abc'};
var blob = new Blob([JSON.stringify(data)], {type : 'octet/stream'});

downloadBlob('myData.json', blob)

The full solution which shows how to download blobs with ngResource is here

2016-05-02

相关问答

更多

Django + Angular2:如何从数据库中获取数据?(Django + Angular2: How to fetch data from database?)

使用Django创建REST api端点(使用DRF作为标准REST api或使用vanilla django为请求生成json响应并将其称为REST api)。 例如: /product/:id是您创建的api终点,用于获取Django中特定产品的详细信息 然后使用Angular通过这些API请求并获取响应并使用该数据执行任何操作。 例如:当用户点击该产品时,向/product/1发送获取请求以获取PK = 1的产品的详细信息。 浏览Github获取一些灵感。 Create REST api e ...

分类Django + AngularJS真实世界的例子(Categorize Django + AngularJS real world examples)

Django , Angular , Bootstrap , Gulp - Cookiecutter种子 项目 : https : //github.com/bearstech/cookiecutter-Django-bootstrap-angular/ 资产构建系统 : gulp和javascript,html, bootstrap REST api :没有 3路数据绑定 :没有 使用djangular :不 许多Django应用程序 :没有 部署自动化 :没有 在生产上运行 :没有 自己的文档 ...

Django注册兼容性问题与Django 1.7(Django-registration compatibility issue with django 1.7)

不要使用PyPI提供的django注册。 它不支持Django 1.7,它似乎永远不会。 回购维护者已退位,该项目似乎无人维护。 在Github上有一个可用于Django 1.7的维护叉: https://github.com/macropin/django-registration 它可以从PyPI以django-registration-redux的形式获得。 https://pypi.python.org/pypi/django-registration-redux/ 您可以使用pip进行安 ...

django休息角登录(django rest angular login)

我能想到的唯一“更好”的做法是: from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['POST']) def login(request): data = request.DATA # authenticate using data dict return Response({'status': 'ok'}) 这样您 ...

angular2中的systemjs.config.js(systemjs.config.js in angular2)

好吧,首先你要告诉npm软件包的位置,通常在根目录,因此: paths: { // paths serve as alias 'npm:': 'node_modules/' } 然后你给你将要使用的包给别名(快捷方式名称),在这种情况下是角度和一些第三方库,如rxjs,... map: { // our app is within the app folder app: 'dist', main: 'main.js', ...

如何重置Angular JS中的文件上传控件(How to reset the file upload control in Angular JS)

设置id到file upload control HTML: <input id= "control" type="file" name="files" ng-files="getTheFiles($files)" /> 控制器: angular.element("#control").value = ""; Set an id to file upload control Html: <input id= "control" type="file" name="files" ng-files ...

在Angular / Django应用程序中突然断开URL和链接(URLs and linking abruptly broken in Angular / Django app)

根据这篇文章, $location干扰某些版本的UI-Bootstrap,并可能对您的URL产生负面影响。 从我的控制器中删除了影响此代码的$location依赖项之后,我能够修复我的URL并使我的所有锚链接和SPA链接再次工作。 As per this article, $location interferes with some versions of UI-Bootstrap and can have adverse effects on your URLs. After removing ...

相关文章

更多

最新问答

更多
  • Android宽度:100%修复(网站接管问题)(Android width:100% fix (website takeover issue))
  • C ++函数/方法设计的良好实践(Good practice in C++ function/method design)
  • 计算其他表中不存在的所有记录 - SQL查询(Count all records that does not exist to other table - SQL Query)
  • 为什么我要用JPA共享ID?(Why do I get shared Ids with JPA?)
  • asp.net - 如何显示来自html格式的数据行的字段(asp.net - how to display a field from data row that is in html format)
  • 我们如何使用ActiveRecord从连接表中删除行?(How can we delete rows from a join table by using ActiveRecord?)
  • ng-class搞乱了类的顺序(ng-class messing with the order of classes)
  • oracle 12g无效数字错误(oracle 12g invalid number error)
  • 更改ng-src值onclick(Change ng-src value onclick)
  • 如何在android中自动添加自定义依赖项以创建新项目?(How to add custom dependencies automatically in android for ever a new project is created?)
  • datetime函数在PHP中(datetime function in php)
  • 在javascript中获取会话数组的值(in javascript get the value of a session array)
  • 如何在UTF8中编译LaTeX?(How can I compile LaTeX in UTF8? [closed])
  • Rspec:“array.should == another_array”,但不用担心订单(Rspec: “array.should == another_array” but without concern for order)
  • Logcat错误:无法在android片段中加载视图(Logcat error: unable to load view in android fragments)
  • JavaFX的。(JavaFX. Adding items to the list in different threads is not working)
  • 从GDATA日历资源迁移到Google Calendar Resource api(Migrate from GDATA calendar resource to Google Calendar Resource api)
  • SSRS 2008 - 以零情景处理分割(SSRS 2008 - Dealing with division by zero scenarios)
  • 我如何以编程方式添加一个listView列标题的点击事件(How can I add a listView column header a click event programmatically)
  • Wxpython:无法检索有关列表控件项XXX的信息(Wxpython: Couldn't retrieve information about list control item XXX)
  • 使用Tortoise SVN在SVN存储库中移动目录(Move Directory across SVN repository using Tortoise SVN)
  • 天蓝色服务结构集群中的web api无状态服务是否在一段时间不活动后进入休眠状态?(Do web api stateless services in azure service fabric cluster go to sleep after a period of inactivity?)
  • 我可以设置intelliJ来突出显示PHP编码风格吗?(Can I set intelliJ to highlight php coding style?)
  • 用javafx创建一个Truetype字体文件(Creating a Truetype Font file with javafx)
  • Spring ftp配置错误(Spring ftp configuration is wrong)
  • 使用gsub去除多个字符(Using gsub to strip multiple characters)
  • 续订推送证书并保持当前的App Store App正常工作(Renew Push certificate and keep current App Store App working)
  • js:ES5和ES6之间关于'this'关键字用法的一个令人困惑的观点(js: one confusing point about 'this' keyword usage between ES5 and ES6)
  • window.onload vs $(document).ready()(window.onload vs $(document).ready())
  • 在Swift中,如何声明一个符合一个或多个协议的特定类型的变量?(In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?)