📅  最后修改于: 2023-12-03 15:14:44.171000             🧑  作者: Mango
在Web应用程序中,文件上传是一个常见的需求。Django提供了很好的支持,可以很容易地实现文件上传并将其保存到服务器。
首先,我们需要创建一个包含文件上传字段的表单。可以使用Django的form
来创建表单。在这个例子中,我们需要上传一个图片文件,所以我们需要一个包含FileField
的表单。
# forms.py
from django import forms
class UploadFileForm(forms.Form):
file = forms.FileField()
下一步是创建视图,该视图处理上传的文件并保存它们。在Django中,可以使用FileUploadHandler
和request.FILES
处理文件上传。在以下例子中,我们将上传的文件保存到服务器的media
目录中。
# views.py
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
from .forms import UploadFileForm
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
fs = FileSystemStorage()
filename = fs.save(file.name, file)
uploaded_file_url = fs.url(filename)
return render(request, 'upload.html', {
'uploaded_file_url': uploaded_file_url
})
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
我们需要在urls.py文件中添加路由,以便能够接收文件上传请求。
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('upload/', views.upload_file, name='upload_file'),
]
最后,我们需要创建模板以便渲染上传表单和上传成功的提示信息。
<!-- upload.html -->
{% extends 'base.html' %}
{% block content %}
<h2>Upload a file</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-primary" type="submit">Submit</button>
</form>
{% if uploaded_file_url %}
<p>Uploaded file: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
<img src="{{ uploaded_file_url }}" alt="Uploaded image">
{% endif %}
{% endblock %}
以上就是Django文件上传的一个完整例子。当您访问上传页面并上传文件时,它将被保存到服务器,并显示一个链接或图像,以便您查看或下载上传的文件。
代码片段:
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
from .forms import UploadFileForm
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
fs = FileSystemStorage()
filename = fs.save(file.name, file)
uploaded_file_url = fs.url(filename)
return render(request, 'upload.html', {
'uploaded_file_url': uploaded_file_url
})
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
<!-- upload.html -->
{% extends 'base.html' %}
{% block content %}
<h2>Upload a file</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-primary" type="submit">Submit</button>
</form>
{% if uploaded_file_url %}
<p>Uploaded file: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
<img src="{{ uploaded_file_url }}" alt="Uploaded image">
{% endif %}
{% endblock %}