Download anchor link with authorization header

爱⌒轻易说出口 提交于 2019-12-09 14:14:28

问题


I have a link that I would like to add to my javascript (Marionette/Backbone) single page application that will download an Excel file to the user's local drive via the browser's file save. A typical HTTP request would be:

GET /api/v1/objects/?format=xls HTTP/1.1
Authorization: ApiKey username:apikey
Host: api.example.com
Connection: close
User-Agent: Paw 2.0.5 (Macintosh; Mac OS X 10.9.2; en_US)
Content-Length: 0

Which results in the following typical response:

HTTP/1.1 200 OK
Server: gunicorn/18.0
Date: Tue, 06 May 2014 03:09:02 GMT
Connection: close
Transfer-Encoding: chunked
Vary: Accept
Content-Type: application/vnd.ms-excel
Content-Disposition: attachment; filename="filename.xls"
Cache-Control: no-cache

<<CONTENT HERE>>>

I'd like to do this with a simple anchor element styled as a button as this would invoke the browser's file storage machinery. Something similar to:

<a href="/api/v1/objects/?format=xls" class="btn btn-primary pull-right">Download to Excel file</a>

I'm not clear on how I get the authorization header to be passed when doing this via an anchor link -- or perhaps I'm just not thinking and there is a better way.

My backend is a Django web app using Tastypie.


回答1:


This not possible, because the only way to add HTTP headers is using the XHR, but XHR cannot be used to download files.

You could however use cookies to do that.

  1. Just set the cookie, with a returned value from the server.
  2. Wait till the user clicks the link.
  3. Invalidate the cookie after the user clicked the link.


来源:https://stackoverflow.com/questions/23485857/download-anchor-link-with-authorization-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!