如何使用django创建下载链接



我正在使用django使用我自己的项目。我正在尝试使用django下载文件。我使用django完成了文件上传。但是我不知道如何在django中创建文件下载链接。example(test.java,我的域是example.com,端口是9001,介质文件夹是/media我只想下来https://example.com:9001/media/test.java就这样。我搜索了所有的方法,但没有线索。。这是我的密码。view.py->上传部分

@csrf_exempt
def index(request):
return render(request, 'useraccount/index.html', {})
@csrf_exempt
def file_list(request):
return render(request, 'useraccount/list.html', {})
@csrf_exempt
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('file_list')
else:
form = UploadFileForm()
return render(request, 'useraccount/upload.html', {'form': form})

upload.html

<html>
<head><title>Upload Test</title></head>
<body>
<form action="upload/"
method="post"
enctype="multipart/form-data">
File:
<input type="file"
name="file"
id="id_file" />
<input type="submit" value="UPLOAD" />
</form>
</body>
</html>

upload.html

{% extends 'useraccount/index.html' %}
{%  block content %}
<h2>Upload file</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit">Upload file</button>
</form>
{% endblock %}

list.html

{% extends 'useraccount/index.html' %}
{% block content %}
<h2>The image has been uploaded!!</h2>
{% endblock %}

forms.py

from django import forms
from .models import UploadFileModel
class UploadFileForm(forms.ModelForm):
class Meta:
model = UploadFileModel
fields = {'title', 'file'}

url.py

from django.urls import path, include
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
path('upload/', views.upload_file, name='upload_file'),
path('list/', views.file_list, name='file_list'),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

要下载存储在数据库中的图像,它将是:

简单示例

视图.py

def download_image(self, imageid):
image = UploadFileModel.objects.get(pk=imageid)
image_buffer = open(image.file.path, "rb").read()
content_type = magic.from_buffer(image_buffer, mime=True)
response = HttpResponse(image_buffer, content_type=content_type);
response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(image.file.path)
return response

urls.py

path('downloadimage/<str:imageid>/$', views.download_image, name='download_image'),

template.html

<a href="{% url 'useraccount:download_image' imageid=<id_of_image> %}" type="button">Download image</a>

注意:请用所需的图像id替换模板中的<id_of_image>

您可以通过url方法生成url文件,如

in.py:

my_file_field.url

在模板中:

<a href="{% my_file_field.url %}"> file link ! </a>

参见django的文档https://docs.djangoproject.com/en/dev/topics/files/

最新更新