Crated function to allow users download pdf files by link. Works fine, the only problem that what user save is .html. So all files are file.pdf.html.
def download(request,ticket_id):
ticket_path = str(Ticket.objects.get(id=ticket_id).upload)
with open('files/media/' + ticket_path, 'rb') as pdf:
response = HttpResponse(pdf.read())
response['content_type'] = 'application/pdf'
response['Content-Disposition'] = 'attachment;filename="file.pdf"'
return response
Why?
You should move content_type into HttpResponse(pdf.read(), content_type='application/pdf'), it's an attribute of HttpResponse
Related
This might perhaps be a simple question, but I somehow just can not find the solution. Django offers a lot about uploading file, but how do I do to download a file.
Let's assume we have a button on HTML on uploads/something.txt as a file.
I tried with django.views.static.serve, however what this did it would open a file on webpage.
My question is simple: What is the best and most pythonic way for user of our website to download a file?
You need to read that file.
Serve it using HttpResponse along with proper content type.
Here's some sample code:
content = open("uploads/something.txt").read()
return HttpResponse(content, content_type='text/plain')
This should serve a text file.
But as you described, on some browser, it will not ask to download the file, rather, it would show it in the browser. If you want to show a download prompt, use this:
response = HttpResponse(open("uploads/something.txt", 'rb').read())
response['Content-Type'] = 'text/plain'
response['Content-Disposition'] = 'attachment; filename=DownloadedText.txt'
return response
However, please note that it might be a better idea to serve static contents or uploaded files via nginx or the reverse proxy of your choice. Sending large files through Django might not be the most optimum way of doing that.
import os
from django.conf import settings
from django.http import HttpResponse, Http404
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
Maybe a little late but here is my solution:
def render(self, value):
return format_html('<a href="/media/{0}" download>{0}</a>', value)
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'
I'm working with Django 1.7 and Python 3.4.
I have a model like this one:
class ImageModel(models.Model):
image = models.ImageField(verbose_name='image', upload_to='uploaded_images/')
Now I want to download image which is saved in /static/uploaded_images/.
For example I have a link like this: www.example.com/image/download/1, where 1 is id of ImageModel object.
Now i have a view:
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
( what I need to do? )
What next? How to create a view that will force download of that image?
You can try this code, maybe need some caveats:
from django.core.servers.basehttp import FileWrapper
import mimetypes
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
wrapper = FileWrapper(open(img.file)) # img.file returns full path to the image
content_type = mimetypes.guess_type(filename)[0] # Use mimetypes to get file type
response = HttpResponse(wrapper,content_type=content_type)
response['Content-Length'] = os.path.getsize(img.file)
response['Content-Disposition'] = "attachment; filename=%s" % img.name
return response
I'm assuming there is a field .name in your ImageModel to get the name of the file in the second-to-last line ...filename=%s" % img.name You should edit the code to fit your project.
There is a field in an ImageField that is file, in the code here I use img.file to get the path to the file, you should change that for img.YOUR_IMAGE_FIELD.file or anything you need to get the path to the image
You need to use Content-Disposition header, take a look here:
Generating file to download with Django
Django Serving a Download File
A class based views-type exampe of this would be like this (i'm using python-magic to get the correct content-type for the file):
import os
import magic
from django.views.generic import View
from django.http import HttpResponse
from .models import ImageModel
class ImageDownloadView(View):
def get(self, request, *args, **kwargs):
image = ImageModel.objects.get(pk=self.kwargs['image_id'])
image_buffer = open(image.file.path, "rb").read()
content_type = magic.from_buffer(image_buffer, mime=True)
response = HttpResponse(image_buffer, content_type=content_type);
response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(image.file.path)
return response
This works for Django 1.10.7 but shouldn't be that different for Django 1.7
The other two answers are ok, but as advertised in many places using Django to serve an static file is not recommended for performance reasons. It is better to serve it using your web server (nginx/apache...).
You don't need an extra view to serve static files. Simply render a link to the file in your template:
Download this image!
Where object is an instance of ImageModel.
See django.db.models.fields.files.FieldFile.url
If you really want to have a view in an URL like www.example.com/image/download/1 you can simply write a view that redirect to the image URL obtained from the field.
Here is your cross browser safe download for files containing any character type
# Even better as it works in any browser (mobile and desktop)
def safe_name(file_name):
"""
Generates a safe file name, even those containing characters like ? and &
And your Kanji and Cyrillics are supported!
"""
u_file_name = file_name.encode('utf-8')
s_file_name = re.sub('[\x00-\xFF]', lambda c: '%%%02x' % ord(c.group(0)), u_file_name)
return s_file_name
# Handled by url(r'^/image/download/(\d+)/.+$
def safe_download_image(request, image_id):
"""
Safely downloads the file because the filename is part of the URL
"""
img = ImageModel.objects.get(id=image_id)
wrapper = FileWrapper(open(img.file)) # img.file returns full path to the image
content_type = mimetypes.guess_type(filename)[0] # Use mimetypes to get file type
response = HttpResponse(wrapper,content_type=content_type)
response['Content-Length'] = os.path.getsize(img.file)
# This works for most browsers, but IE will complain sometimes
response['Content-Disposition'] = "attachment;"
return response
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
redirect_do = safe_name(img.name)
return HttpResponseRedirect('/image/download/' + img_id + '/' + redirect_to)
It's doesn't work. I did something like this:
wrapper = FileWrapper(img.file) # img.file returns full path to the image
content_type = mimetypes.guess_type(str(img.file))[0] # Use mimetypes to get file type
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize(str(img.file))
response['Content-Disposition'] = "attachment; filename=%s" % img.name
where img points to my ImageField field. File is downloaded, but I can't open it. xUbuntu image viewer seys 'Not a JPEG file. starts with 0x89 0x50'
I want users to be able to download file from my django web app. I wrote the below codes, but when I download a file, the file will turn into an error file. It won't open and the total size of the file would be 0 bytes.
Models:
class Emov(models.Model):
User=models.ForeignKey(User)
mov_file=models.FileField(upload_to='miiv')
mov_name=models.CharField(max_length=50)
email=models.EmailField() #email of the uploader
download_count=models.PositiveIntegerField(default=0)
#other fields follows
#property
def pretty_name(self):
return "{0}.{1}".format(slugify(self.title),
os.path.splitext(self.mov_name.name)[1])
Views:
def document_view(request,emov_id):
fileload=Emov.objects.get(id=emov_id)
response=HttpResponse()
response["Content-Disposition"]= "attachment; filename={0}".format(fileload.pretty_name)
response['X-Accel-Redirect']="/protected/{0}".format(fileload.mov_name.name)
return response
Nginx
location /protected/ {
internal;
root /C:/Python27/Scripts/env/Scripts/digi/media/miiv/;
}
What am I missing?
Try to do it like this:
fileload = Emov.objects.get(id=emov_id)
filename = fileload.mov_file.name.split('/')[-1]
response = HttpResponse(fileload.mov_file, content_type='text/plain') # your content type
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
See:
https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment
Hope it helps.
EDIT:
FileField.url attribute you should be able to pass a path to your files (like /protected/). https://docs.djangoproject.com/en/dev/ref/models/fields/#filefield-and-fieldfile
I am displaying the list of objects in the html table.
i have the download link in front of every row which i want them to download the linked file.
I have made this function
def make_downloadable_link(path):
#Prepare the form for downloading
wrapper = FileWrapper(open(mypath))
response = HttpResponse(wrapper,'application/pdf')
response['Content-Length'] = os.path.getsize(mypath)
fname = mypath.split('/')[-1]
response['Content-Disposition'] = 'attachment; filename= fname'
return response
This is working fine if i use it for hard coded path in view for single file. But i want to make a generic view so that it works on all the files in the table
I hav the path of the file avaiable in object.path variable but i am confused how can i pass the path object to the downlaod file view. because i want to hide that actual path from the user.
I don't know what to write in the URLs.py file fo that download file view
What would you like to do is get actual file path from object. And as you have said the file path is stored in object.path that makes it easy.
For example:
urls.py
url(r'^download/(?P<object_id>\d+)/$', "yourapp.views.make_downloadable_link", name="downloadable")
In views.py:
def make_downloadable_link(object_id):
# get object from object_id
object = ObjectModel.objects.get(id=object_id)
mypath = object.path
#prepare to serve the file
wrapper = FileWrapper(open(mypath))
response = HttpResponse(wrapper,'application/pdf')
response['Content-Length'] = os.path.getsize(mypath)
fname = mypath.split('/')[-1]
response['Content-Disposition'] = 'attachment; filename= fname'
return response