domingo, 19 de octubre de 2008

force download django

When you serve a document,image,file from a Web server, you might want to immediately prompt the user to save the file directly to the user's disk, without opening it in the browser.

You can use the content-disposition header to override the default behavior.

The code below shows how-to do this in python/django:

import mimetypes, os

def download_view(request, filename):
    file = open(filename,"r")
    mimetype = mimetypes.guess_type(filename)[0]
    if not mimetype: mimetype = "application/octet-stream"

    response = HttpResponse(file.read(), mimetype=mimetype)
    response["Content-Disposition"]= "attachment; filename=%s" % os.path.split(filename)[1]
    return response

No hay comentarios: