Home > Enterprise >  Django call function to save file cannot work
Django call function to save file cannot work

Time:12-05

I am create Django project and create function for download file, But my project cannot work, File not response to save

view.py

from django.http.response import HttpResponse
from django.conf import settings
from django.http import HttpResponse, Http404

def index(request):
     BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     filename = 'my_file.json'
     filepath = BASE_DIR   '/filedownload/'   filename
     download(request,filepath)
     return HttpResponse('Download File')

def download(request, path):
     file_path = path
     if os.path.exists(file_path):
     with open(file_path, 'rb') as fh:
          response = HttpResponse(fh.read(), content_type="application/x-download")
          response['Content-Disposition'] = 'inline; filename='   os.path.basename(file_path)
          return response
     raise Http404

How can I solve this?

CodePudding user response:

Your download() returns response to your index() and your index() returns its own response(not a response of download()). If you returns response of download() like below, it will works.

import os
from django.http.response import HttpResponse
from django.conf import settings
from django.http import HttpResponse, Http404

def index(request):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    filename = 'my_file.json'
    filepath = BASE_DIR   '/filedownload/'   filename
    return download(request,filepath)

def download(request, path):
    file_path = path
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/x-download")
            response['Content-Disposition'] = 'inline; filename='   os.path.basename(file_path)
            return response
    raise Http404
  • Related