Python Django - Как загрузить файл на клиентский компьютер в проекте django - PullRequest
1 голос
/ 09 марта 2020

Я новичок в python, я создал небольшое Django приложение для загрузки данных в формате Excel. он загружается в папку проекта или по заданному пути (на сервере).

, но когда я нажимаю URL-адрес с клиентского компьютера, он должен загружаться на клиентском компьютере, но загружается только на моем сервере. Пожалуйста, предложите подходящий метод (код) для загрузки файла Excel только на клиентском компьютере.

Заранее спасибо.

------- код -------

try:
    cursor = connection.cursor()
    cursor.execute("""select * from table""")

    columns = [desc[0] for desc in cursor.description]
    data = cursor.fetchall()
    result = len(data)
    print("No of records :" ,len(data))
    df = pd.DataFrame(list(data), columns=columns)

    home = os.path.expanduser("~")
    print('Home path------------',home)
    download_location = os.path.join(home,'Downloads')
    print('download path------------',download_location)

    filename = 'django_simple.xlsx'

    writer = pd.ExcelWriter(download_location+'/'+ filename)
    df.to_excel(writer, sheet_name='Hundai')
    writer.save()

    print("File saved successfully!")
    cursor.close()
except:
    print("There is an error")    
finally:
    if (connection):
        connection.close()
        cursor.close()
        print("The MSSQL connection is closed")   

return render(request,'result.html',{'result': result})

Ответы [ 2 ]

1 голос
/ 09 марта 2020

Посмотрите этот очень простой, но эффективный код.

import pathlib
from django.http import FileResponse

def download(request):
    file_server = pathlib.Path('the_path_of_your_file_to_download')
    if not file_server.exists():
        messages.error(request, 'file not found.')
    else:
        file_to_download = open(str(file_server), 'rb')
        response = FileResponse(file_to_download, content_type='application/force-download')
        response['Content-Disposition'] = 'inline; filename="a_name_to_file_client_hint"'
        return response
    return redirect('a_url_path')
0 голосов
/ 09 марта 2020
from django.http import HttpResponse


try:
    cursor = connection.cursor()
    cursor.execute("""select * from table""")

    columns = [desc[0] for desc in cursor.description]
    data = cursor.fetchall()
    result = len(data)
    print("No of records :" ,len(data))
    df = pd.DataFrame(list(data), columns=columns)

    home = os.path.expanduser("~")
    print('Home path------------',home)
    download_location = os.path.join(home,'Downloads')
    print('download path------------',download_location)

    filename = 'django_simple.xlsx'

    writer = pd.ExcelWriter(download_location+'/'+ filename)
    df.to_excel(writer, sheet_name='Hundai')
    writer.save()

    print("File saved successfully!")
    cursor.close()

    with open(download_location+'/'+ filename, '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

except:
    print("There is an error")    
finally:
    if (connection):
        connection.close()
        cursor.close()
        print("The MSSQL connection is closed")   

return render(request,'result.html',{'result': result})
...