I
I
Ilya Korol2019-07-03 11:36:23
Django
Ilya Korol, 2019-07-03 11:36:23

How to give an image as a result without using static?

There is a picture in a certain folder.
How to return a picture as a result of a query without using static files (by request) (not by its name, but, let's say, by its number)?
Ps about how to load the page (a function is called with the necessary parameters passed in the url, as a result of which the desired image is returned)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2019-07-04
@welcome32

For example, like this (of course, you need to finish it to suit your needs, but the idea is clear):

spoiler
import os
import mimetypes
from django.http import StreamingHttpResponse
from django.core.servers.basehttp import FileWrapper


def download_file(request):
   the_file = '/some/file/name.png'
   filename = os.path.basename(the_file)
   chunk_size = 8192
   response = StreamingHttpResponse(FileWrapper(open(the_file, 'rb'), chunk_size),
                           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

https://docs.djangoproject.com/en/2.2/howto/output...
https://www.programcreek.com/python/example/52439/...
PS Instead of
from django.core.servers.basehttp import FileWrapper

use from wsgiref.util import FileWrapper
Django > 1.8 doesn't have it.
class wsgiref.util.FileWrapper(filelike, blksize=8192)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question