Django downloads local files to users

To access this function, you need to pass the path of a file. My method is to send a get request through a button button, carrying the path of the file

Import some dependent packages (not necessary)

from django.contrib import messages
from django.shortcuts import render, redirect

The role of messages is to set the prompt box. This can be designed by yourself as needed, and it can be deleted if you don’t need it.

For setting the prompt box, please refer to another article Django background setting prompt box (message box)_django pop-up prompt box_gongzairen's blog-CSDN blog

The following is the code for back-end processing, focusing on downloading files for users

It returns a response object, and there is no way to directly carry the file object back to the web page

def download_file(request):
    # print(request.GET)
    file_path = request.GET['file_path']
    file_name = os.path.basename(file_path)
    quoted_filename = quote(file_name.encode('utf-8'))

    if not file_path:
        messages.warning(request,'没有文件无法下载!')
        return redirect('所要返回的地址')

    if not os.path.exists(file_path):
        messages.warning(request, '找不到对应文件!')
        return redirect('所要返回的地址')
    # 将文件打开为二进制读取模式
    file = open(file_path, 'rb')
    # 创建一个文件响应对象
    response = FileResponse(file)
    # 设置文件类型
    response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    # 设置文件名
    response['Content-Disposition'] = f'attachment; filename={quoted_filename}; filename*=utf-8\'\'{quoted_filename}'
    print(response['Content-Disposition'])
    messages.success(request, '下载成功!')
    return response

 

Guess you like

Origin blog.csdn.net/gongzairen/article/details/131589596