Firefox does not save file with extension - python

I have a view in my Django application which creates a XLSX file and returns it to the user for download:
# Creates the response
response = HttpResponse(output.read(),
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = 'attachment; filename="{}".xlsx'.format(tournament.name)
When I try to download the file in Chrome, it works perfectly: the file is downloaded with filename "blabla.xlsx".
However with Firefox, it is downloaded with filename "blabla" (no extension).
Did you ever encounter this problem?

Related

My download function saves a file with fixed name

I'm using Django 1.8 with Python 3.6.
When I use my download function below, it saves the file with a name fixed to local download directory. But I really want to keep the original name.
I can change the browser to open a download manager, but I want to know how to fix this filename to the original one.
def download(request):
path = "test.jpg" # Original filename that I intend to give.
file_path = os.path.join(settings.MEDIA_ROOT,path)
print("file_path :", file_path)
if os.path.exists(file_path):
readFile = open(file_path,"rb")
response = HttpResponse(readFile.read())
response['Content-Disposition'] ='attachment; filename'+os.path.basename(file_path)
response['Content-type'] = 'image/jpg'
return response
When I download the file, it is autosaved with a name 'Download.jpg', which is the browser's default directory name.
You have missed the =in your response['Content-Disposition'].
This one should work as expected:
response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)

Django Serve .XLSX File and force download

I'm currently using openPYXL in order to open a template file within Django
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, fileName)
username = request.user.username
workbook = load_workbook(file_path)
worksheet = workbook.active
The file is then edited, and saved under a different name(This works fine, I can open the created file and it contains the information desired), however what I'm struggling with is serving this file to the user, I've tried various techniques such as shown below
workbook.save('EvalofSelf1.xlsx')
response = HttpResponse()
file_path = os.path.join(os.path.dirname(os.path.realpath(__name__)), 'EvalofSelf1.xlsx')
response['X-Sendfile'] = file_path
response['Content-Type'] = 'mimetype/submimetype'
response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'DownloadedEval'
All of which serve a file as requested, but the file contains no actual data, is 0kb in size and unopenable, how can I serve up the created file from my Django project directory, retaining all information stored within it?
You're not ever putting the file contents into the response, so naturally it is 0 bytes. X-Sendfile is for a completely different purpose - when you're redirecting to a static server - and needs a URL, not a file path, anyway.
file_path = os.path.join(os.path.dirname(os.path.realpath(__name__)), 'EvalofSelf1.xlsx')
response = HttpResponse(open(file_path, 'rb').read())
response['Content-Type'] = 'mimetype/submimetype'
response['Content-Disposition'] = 'attachment; filename=DownloadedEval.xlsx'

django open a zip file for user to download

Django 1.7, Python 3.4, windows apache 2.4.12 + wsgi
In my program, I generate some csv files and put them in a zip file. I would like to let the user download the zip file, either force download (after file is generated and render response) or a click of button (after display result, user has to click a button to download.)
Currently I am forcing them to download once the zip file is generated on the server.
I have referenced the following links and come up with my code below. But it is always give me this error "'charmap' codec can't decode byte 0x8d in position 80: character maps to " I tried to set it with utf-8 and ascii, and similar errors will be given.
referenced links:
django download file from server to user's machine,or read online
how to serve downloadable zip file in django
https://djangosnippets.org/snippets/365/
Generating file to download with Django
Anyone know why am I getting this error and how to get this to work?
Thank you very much!
zip_filename = time.strftime("%Y%m%d") + ".zip"
with zipfile.ZipFile(zip_filename, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
for s in sql_request:
// generate csv files
zf.write(csv_file)
// close zf
zip_file = open(zip_filename, 'r')
response = HttpResponse(zip_file, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'foo.zip'
return response
If you're on Windows, you might need to change your open line to include the b flag.
zip_file = open(zip_filename, 'rb')

Django Serving a Download File

I'm trying to serve a txt file generated with some content and i am having some issues. I'vecreated the temp files and written the content using NamedTemporaryFile and just set delete to false to debug however the downloaded file does not contain anything.
My guess is the response values are not pointed to the correct file, hense nothing is being downloaded, heres my code:
f = NamedTemporaryFile()
f.write(p.body)
response = HttpResponse(FileWrapper(f), mimetype='application/force-download')
response['Content-Disposition'] = 'attachment; filename=test-%s.txt' % p.uuid
response['X-Sendfile'] = f.name
Have you considered just sending p.body through the response like this:
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)
XSend requires the path to the file in
response['X-Sendfile']
So, you can do
response['X-Sendfile'] = smart_str(path_to_file)
Here, path_to_file is the full path to the file (not just the name of the file)
Checkout this django-snippet
There can be several problems with your approach:
file content does not have to be flushed, add f.flush() as mentioned in comment above
NamedTemporaryFile is deleted on closing, what might happen just as you exit your function, so the webserver has no chance to pick it up
temporary file name might be out of paths which web server is configured to send using X-Sendfile
Maybe it would be better to use StreamingHttpResponse instead of creating temporary files and X-Sendfile...
import urllib2;
url ="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=s&chld=H|0";
opener = urllib2.urlopen(url);
mimetype = "application/octet-stream"
response = HttpResponse(opener.read(), mimetype=mimetype)
response["Content-Disposition"]= "attachment; filename=aktel.png"
return response

downloading archives response corrupts files

wrapper = FileWrapper(file("C:/pics.zip"))
content_type = mimetypes.guess_type(result.files)[0]
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize("C:/pics.zip")
response['Content-Disposition'] = "attachment; filename=pics.zip"
return response
pics.zip is a valid file with 3 pictures inside.
server response the download, but when I am going to open the zip, winrar says This archive is either in unknown format or damaged!
If I change the file path and the file name to a valid image C:/pic.jpg is downloaded damaged too.
What Im missing in this download view?
The problem is that you're not reading it as a binary file :)
This should work:
wrapper = FileWrapper(file("C:/pics.zip", 'rb'))

Categories