Thursday, June 12, 2014

File download script

Greetings! If you recall, a while ago we saw how to write a file upload script. File download is also equally important. Let's see how to write a download script now.

def download (request):
    filename = "/foo/bar/%s.%s" % (name, extension)
    f1 = open (filename, "r")
    response = HttpResponse (f1, mimetype = "type/extension")
    response['Content-Disposition'] = "attachment; filename = foo_bar.extension"
    return response


Ok, now let's examine this code:
  • Specify the file name
  • Open this file in read mode
  • Create HttpResponse object with the following parameters: filename, and mimetype.
  • MIME stands for Multipurpose Internet Mail Extension.
  • Here's a list of all MIME types. Find the appropriate one for the extension you want: http://www.sitepoint.com/web-foundations/mime-types-complete-list/
  • The second filename in the last but one line is the name and extension which the downloaded file should have. For example, your file may be .py, but you might want to make it download as .txt
  • Finally, return the HttpResponse object, and et voila! You have your file ready for download.
Note: As usual, this download will be triggered when the URL that points to the function download in the particular view is accessed.
Cheers!

No comments:

Post a Comment