Downloading the Django Server File

Asked 1 years ago, Updated 1 years ago, 80 views

Thank you for browsing.
I'm afraid this is a very rudimentary question, but let me ask you a question.
I am currently developing WebAPI at Django and would like to handle files.
Therefore, we are arranging the download area of the file by referring to the following website.
https://pc.atsuhiro-me.net/entry/2014/09/28/140421

At this time, if I access a specific URL from my browser, will the file be downloaded? It says "download(request) will download the file", but I don't like it.

I look forward to hearing from you.

python api django

2022-09-30 19:28

1 Answers

The following site
https://pc.atsuhiro-me.net/entry/2014/09/28/140421

Here is an example of downloading a text file posted on this site.

def download (request):
    output=io.StringIO()
    output.write("First line.\n")
    response=HttpResponse(output.getvalue(), content_type="text/plain")
    response ["Content-Disposition" = "filename=text.txt"
    return response

The ability to do this is to create a file-like response inside the server application and have the user download it as a file (in this example, create and download a file called FFirst line. 」 under the filename file.txt), not the server that Laurenentech is looking for.

The English version of Stack Overflow has almost the same question as this one, which suggests that it is better to open the file directly and return it with HttpResponse.

https://stackoverflow.com/a/36394206/10216107

importos
from django.conf import settings
from django.http import HttpResponse

def download (request, path):
    file_path=os.path.join(settings.MEDIA_ROOT, path)
    ifos.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


2022-09-30 19:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.