在Django中處理文件上傳問題通常涉及以下幾個步驟:
from django import forms
class UploadFileForm(forms.Form):
file = forms.FileField()
from django.shortcuts import render
from .forms import UploadFileForm
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# 處理上傳的文件
file = form.cleaned_data['file']
# 保存文件到指定位置
with open('path/to/save/file', 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
return render(request, 'success.html')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<h1>File uploaded successfully!</h1>
from django.urls import path
from .views import upload_file
urlpatterns = [
path('upload/', upload_file, name='upload_file'),
]
通過以上步驟,可以實現在Django中處理文件上傳的功能。在實際應用中,可以根據具體需求進行更多的處理和驗證。