Django中实现点击图片链接强制直接下载的方法

WBOY
Release: 2016-06-10 15:12:36
Original
1740 people have browsed it

本文实例讲述了Django中实现点击图片链接强制直接下载的方法。分享给大家供大家参考。具体分析如下:

当用户点击图片连接时,默认为在浏览器中直接开打图片,这段代码可以让图片链接变成下载

这段代码也非常适合下载大文件,基本不会消耗内存,每次只读取一部分数据到内存,然后提供下载

def Download(request):
  def readFile(fn, buf_size=262144):
    f = open(fn, "rb")
    while True:
      c = f.read(buf_size)
      if c:
        yield c
      else:
        break
    f.close()
  filename = '/usr/local/1.jpg'
  try:
    response = HttpResponse(readFile(file),mimetype='application/octet-stream')
    response['Content-Disposition'] = 'attachment; filename=%s' %'附件'
  except:
    response = HttpResponse('')
  return response
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template