如何使點選超連結後瀏覽器彈出下載框
阿新 • • 發佈:2019-02-13
如果下載的資源和伺服器是同域的,那麼只要在a標籤中新增download屬性即可。
<a href="http://127.0.0.1:8000/a.jpg" download="a.jpg">下載</a>
如果下載的資源和伺服器是不同域的,那麼新增download屬性是沒有效果的。
<a href="http://www.baidu.com/xxx.jpg" download="a.jpg">下載</a>
解決辦法:
在views.py中定義以下方法:
import urllib2
def file_download(request):
url=request.REQUEST['url' ]
filename=request.REQUEST['filename']
sourceFile = urllib2.urlopen(url)
response=HttpResponse(sourceFile.read())
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename)
return response
然後將a標籤的href改一改就行了:
<a href="http://127.0.0.1:8000/file_download?url=http://www.baidu.com/xxx.jpg&filename=a.jpg">下載</a>