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"
Related
I created a function to create multiple PDFs with Weasyprint, zip them together and download the zip file. When trying to extract the folder on Windows 10 with the in-house zip program i get this error:
"An unexpected error is keeping you from copying the file. [...] Error 0x80070057" <
I can skip the error and the files get extracted. However in the best case scenario I'd like to prevent this error.
def get_all_shareholder_reports(request):
current_shareholders = list(models.objects.all())
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "a") as zip_file:
for shareholder in current_shareholders:
pdf_file_handle = io.BytesIO()
context_dict = get_report_details(pk=shareholder.shareholder_id)
html_string = render_to_string('template.html',
context_dict)
html_handler = HTML(string=html_string, base_url=request.build_absolute_uri())
html_handler.write_pdf(target=pdf_file_handle)
pdf_file_handle.seek(0)
pdf_string = pdf_file_handle.getvalue()
pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
context_dict['shareholder'].surname,
datetime.datetime.now().strftime(
"%d_%m_%Y_%H:%M:%S"))
zip_file.writestr(zinfo_or_arcname=pdf_file_name, data=pdf_string)
zip_buffer.seek(0)
response = HttpResponse(zip_buffer.getvalue(), content_type="application/x-zip-compressed")
response['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip'
return response
I figured it out: The zip file didn't like the ":" in the filename. Removing them fixed the issue.
pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
context_dict['shareholder'].surname,
datetime.datetime.now().strftime(
"%d_%m_%Y_%H_%M_%S"))
You basically need to clean the filename for all reserved characters in Windows: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
So the following should do it "filename".replaceAll("[<>:\"/\\\\|?*]", "")
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
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')
I have made a view to serve some file.tar.gz but when I download it, the file is not compressed.
Files on server, where my app is running has 63 438 bytes:
-rw-r--r-- 1 root root 63448 Nov 5 14:13 file.tar.gz
but when I download it it has 716 800 bytes.
This is my downloading function:
def download_logs(request):
""" View returning file to download """
file_path = request.GET['filepath']
original_filename = file_path.split("/")[-1]
try:
file_loaded = open(file_path, 'rb')
except IOError as err:
LOG.debug(err)
LOG.debug("File %s does not exist", file_path)
return error_view(request, "IOError", "File no longer exists.")
response = HttpResponse(file_loaded.read(), 'application/x-gzip')
file_loaded.close()
file_type, encoding = mimetypes.guess_type(original_filename)
if file_type is None:
file_type = 'application/octet-stream'
response['Content-Type'] = file_type
response['Content-Length'] = str(os.stat(file_path).st_size)
if encoding is not None:
response['Content-Encoding'] = encoding
# To inspect details for the below code, see http://greenbytes.de/tech/tc2231/
if u'WebKit' in request.META['HTTP_USER_AGENT']:
# Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly.
filename_header = 'filename=%s' % original_filename.encode('utf-8')
elif u'MSIE' in request.META['HTTP_USER_AGENT']:
# IE does not support internationalized filename at all.
# It can only recognize internationalized URL, so we do the trick via routing rules.
filename_header = ''
else:
# For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers).
filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(original_filename.encode('utf-8'))
response['Content-Disposition'] = 'attachment; ' + filename_header
return response
I image that there is a problem with the way how I open the file, I just could not find right solution.
If you need to serve a tar.gz file do this,
tar = tarfile.open("file_name.tar.gz", "r")
response = HttpResponse(tar, content_type='application/tar+gzip')
response['Content-Disposition'] = 'attachment; filename="file_name.tar.gz"'
return response
As Klaus D. said in comment this was a problem with encoding.
When I changed
if encoding is not None:
response['Content-Encoding'] = encoding
to
response['Content-Encoding'] = 'tar'
Everything stated to working properly.
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.
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.