django 1.4. I am trying to develop a function to deploy download. I didnt get the right result. I attach my code at below. When I download after click hyperlink, I got a 0 bytes file. The Content-Length is 0 in debug mode. I have read many related questions, I got some clues, but still confused, since I got 0 bytes file after download. can anyone help modify codes below, thx for ur time.
def download_file(request, filepath, filename):
path_to_file = filepath+"\\"+filename
serverfile = file(path_to_file, 'rb')
response = HttpResponse(mimetype='application/force-download')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename)
response['Content-Length'] = serverfile.tell()
return response
.tell()gives the current position in a file. Since you haven’t read any of the file, your current position will be at position 0.You could use
os.stat(path_to_file).st_sizeto give the file size in bytes. Note that you should also useos.path.join(filepath, filename)to get the full (OS-independent) path to the file, rather than concatenating manually.