django error:can't specify the download filename - python

def download(request):
f = open("next_op.xls")
data = f.read()
f.close()
response = HttpResponse(data, content_type = './application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="nextop.xls"'
return response
When I use this code, I can download the file correctly, but the file name is invalid. I get the file name "download", and I found the response header doesn't include the Content-Disposition after I download the file.

you may need this:
fd = open(file, 'rb')
return FileResponse(fd, as_attachment=True, filename='xxx')

Related

compress with pyminizip and return to response

I am trying to compress data with pyminizip and return the data as response in a Django project as follows
def get_csv_file(request):
response = HttpResponse(content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="member.zip"'
users = User.objects.all()
file_path = os.path.join(tempfile.gettempdir(), 'member.csv')
f = open(file_path, 'w')
file_writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL)
for user in users:
file_writer.writerow([user.username, user.email])
f.close()
pyminizip.compress(file_path, "members", response, "pass", int(1))
return response
getting this error
ValueError at /get_csv_file/
expected arguments are compress(srcfile, prefix, zipfile, password, compress_level)
The "zipfile" argument in the pyminizip.compress function is expecting a file path to write a zip file, howeer you've supplied a HttpResponse object, so it doesn't know what to do with it.
You'll need to temporarily write the file to disk, and then read it to be able to send it back

Response ZIP file by Django

I try to download img from url, add it to zip archive and then response this archive by Django HttpResponse.
import os
import requests
import zipfile
from django.http import HttpResponse
url = 'http://some.link/img.jpg'
file = requests.get(url)
data = file.content
rf = open('tmp/pic1.jpg', 'wb')
rf.write(data)
rf.close()
zipf = zipfile.ZipFile('tmp/album.zip', 'w') # This file is ok
filename = os.path.basename(os.path.normpath('tmp/pic1.jpg'))
zipf.write('tmp/pic1.jpg', filename)
zipf.close()
resp = HttpResponse(open('tmp/album.zip', 'rb'))
resp['Content-Disposition'] = 'attachment; filename=album.zip'
resp['Content-Type'] = 'application/zip'
return resp # Got corrupted zip file
When I save file to tmp folder - it's ok, I can extract it.
But when I response this file I get 'Error 1/2/21' on MacOS or Unexpected EOF if I try to open in Atom editor (just for test).
I also used StringIO instead of saving zip file, but it doesn't influence the result.
If you're using Python 3, you'd do it like this:
import os, io, zipfile, requests
from django.http import HttpResponse
# Get file
url = 'https://some.link/img.jpg'
response = requests.get(url)
# Get filename from url
filename = os.path.split(url)[1]
# Create zip
buffer = io.BytesIO()
zip_file = zipfile.ZipFile(buffer, 'w')
zip_file.writestr(filename, response.content)
zip_file.close()
# Return zip
response = HttpResponse(buffer.getvalue())
response['Content-Type'] = 'application/x-zip-compressed'
response['Content-Disposition'] = 'attachment; filename=album.zip'
return response
That's without saving the file. Downloaded file goes directly to io.
To response saved file, use this syntax:
response = HttpResponse(open('path/to/file', 'rb').read())

Downloading file from FileField in Django with a HTTP link in a HTML file

I create a link that when a user press it, it will download a pdf file from the media folder in Django to the users machine.
I tried different methods but all were wrong for me. It tells me that the file can not be found, or the code is running but the file is corrupted.
My Html link:
<td> Download</td>
My url pattern links into a view:
url(r'^download/$', views.DownloadPdf),
My FileField is like this:
upload_pdf = models.FileField()
Following snippet code is the view that downloads a corrupted pdf:
def DownloadPdf(request):
filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf'
response = HttpResponse(content_type='application/pdf')
fileformat = "pdf"
response['Content-Disposition'] = 'attachment;
filename=thisismypdf'.format(fileformat)
return response
So, what I have to do to make it working ?
with open(os.path.join(settings.MEDIA_ROOT, 'Invoice_Template.pdf'), 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
return response
#Sergey Gornostaev 's code just work perfect, but i post below my code because it is a aproach in a differect way.
I correct a little bit my code:
def DownloadPdf(request):
path_to_file = '/home/USER/PycharmProjects/MyProject/media /Invoice_Template.pdf'
f = open(path_to_file, 'r')
myfile = File(f)
response = HttpResponse(myfile, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=filename'
return response
But only in pdf file ( works with txt files ) gives me that error:
'utf-8' codec can't decode byte 0xe2 in position 10

Django define name of file to serve

I have wrote a code which let user to download a file. This is the code :
def download_file(request, ref):
filepath = "/home/jedema/code_"+ref+".txt"
filename = os.path.basename(filepath)
final_filename = "code.txt"
return serve(request, filename, os.path.dirname(filepath))
I want to define the file name that user will download. At the moment, the name of downloaded file is the URL after my domain name.
Do you know how to define the name of file downloaded by user ?
You need to set the Content-Dispositionheader in your response. First of all you shouldn't use the serve() view, to deliver the file, because it only works as long as DEBUG = True is set.
With a look at the Django Docs something like the following should do the trick
def download_file(request, ref):
filepath = "/home/jedema/code_"+ref+".txt"
filename = os.path.basename(filepath)
final_filename = "code.txt"
with open(filepath) as f:
response = HttpResponse(f.read(), content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s"' % final_filename
return response
I haven't tested it but it should be a hint into the right direction

Unknown and Damaged Archive in django

This is code to download files but when file downloads and i open them :the archive is unknown and damaged. Can you please help me to solve this problem here code is:
def download(request):
file_name =request.GET.get('file_name', '')
the_file = "C:\\Users\\CV_Uploads\\uploadfiles\\uploadfiles\\uploaded_files\\1395901478_89_uploadfiles.rar"
filename = os.path.basename(the_file)
response = HttpResponse(FileWrapper(open(the_file)),
content_type=mimetypes.guess_type(the_file)[0])
response['Content-Length'] = os.path.getsize(the_file)
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response
When you are dealing with paths you should use raw string .
use
the_file = r"C:\Users\CV_Uploads\uploadfiles\uploadfiles\uploaded_files\1395901478_89_uploadfiles.rar"

Categories

Resources