html頁面如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <p align="center">請輸入文件名:<input type="text" name="filename" /></p> <p align="center"><input type="submit" value="下載" /></p> </form> </body> </html>
效果如圖:

views視圖函數如下:
根據傳遞的文件名稱,先判斷用戶輸入是否為空,再判斷文件路徑是否存在,如果存在就返回文件
from django.http import HttpResponse, FileResponse def FileDownload(request): if request.method == "GET": return render(request, "download.html") if request.method == "POST": file_name = request.POST.get("filename") print("獲取到的文件名是:{}".format(file_name)) if file_name: path = '{}\\up_image\\{}'.format(settings.MEDIA_ROOT, '{}.png'.format(file_name)) if os.path.exists(path) == True: # 判斷文件是否存在 save_path = open(path, "rb") response = FileResponse(save_path) response['Content-Type'] = 'application/octet-stream' filename = 'attachment; filename=' + '{}.png'.format(file_name) # TODO 設置文件名的包含中文編碼方式 response['Content-Disposition'] = filename.encode('utf-8', 'ISO-8859-1') # response['Content-Disposition'] = 'attachment;filename='+ '{}.png'.format(file_name) return response else: return HttpResponse("文件不存在") else: return HttpResponse("請輸入正確的文件名")
urls配置訪問地址:
如圖:

訪問下載如圖:

抓包如圖:

