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配置访问地址:
如图:
访问下载如图:
抓包如图: