0

i am writing this function in views.py file:

def download(request):

    file = open("D:\wamp\www\User_App.rar","r")
    mimetype = mimetypes.guess_type("D:\wamp\www\User_App.rar")[0]
    if not mimetype: mimetype = "application/octet-stream"

    response = HttpResponse(file.read(), mimetype=mimetype)
    response["Content-Disposition"]= "attachment; filename=%s" % os.path.split("D:\wamp\www\User_App.rar")[1]
    return response

to download file but when that downloads and i open this it is damaged. how to solve this problem.

Tameen Malik
  • 1,258
  • 6
  • 17
  • 45
  • 1
    A few comments on code style. `file` is a reserved word in python, you shouldn't name your variables `file`. Also: use a context manager to open files, ie `with open(filename) as f: response = HttpResponse(f.read(), mimetype=mimetype)` – room2web Mar 25 '14 at 12:31
  • any more suggestions @room2web? – Tameen Malik Mar 25 '14 at 12:47
  • 1
    Don't use one-line if statements :). PEP8 frowns upon them. That said. Read PEP8 :). Does mimetypes.guess_type(...) always return a non-empty list? If not, you should use `try: ... expect IndexError: ...` to get the mimetype (google Duck Typing). – room2web Mar 26 '14 at 10:11

1 Answers1

3

Open files in binary mode:

file = open(r"D:\wamp\www\User_App.rar", "rb")

as opening files in text mode means line endings are translated to a platform-neutral \n character.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343