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.
Related
Hi I'm creating pdf file but I face an error [WinError 2] The system cannot find the file specified but I don't know where is the error
if os.path.exists(pdf_file_output):
with open(pdf_file_output, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(pdf_file_output)
return response
Your code is unable to locate the file specified (probably in Windows). There are few reasons:
Wrong file path: Check if that pdf_file_output file path is correct and the file is exist in that location.
Permission problem: Make sure that the current user has permissions to access the file.
Typo in the filename: Check if that there are no typos in the file name and the file name is the same as you're trying to access.
Alternative script that helps you to debug your code:
import os
pdf_file_output = ...
if os.path.exists(pdf_file_output):
with open(pdf_file_output, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename=' +
os.path.basename(pdf_file_output)
return response
else:
print(f"The file '{pdf_file_output}' doesn't exist.")
I have a button which downloads a excel file with extension .xls. I am using module xlrd to parse the file and return it back to the user. However it appears to add the object name into the excel file instead of the data.
How can I return the file to the user with the data rather than the objects name?
View
def download_file(self, testname):
import csv, socket, os, xlrd
extension = '.xls'
path = r"C:\tests\{}_Report{}".format(testname, extension)
try:
f = xlrd.open_workbook(path)
response = HttpResponse(f, content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename={}_Report{}'.format(testname, extension)
return response
except Exception as Error:
return HttpResponse(Error)
return redirect('emissions_dashboard:overview_view_record')
Excel result
Download successful:
Content:
Note: I understand this is an old file format but is required for this particular project.
You are trying to send a xlrd.book.Book object, not a file.
You used xlrd to do your things in the workbook, and then saved to a file.
workbook = xlrd.open_workbook(path)
#... do something
workbook.save(path)
Now you send it like any other file:
with open(path, 'rb') as f:
response = HttpResponse(f.read(), content_type="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename={}_Report{}'.format(testname, extension)
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')
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"