在Django中,可以使用FileField
來實現文件上傳和下載。
文件上傳的步驟如下:
FileField
字段,用于存儲上傳的文件。from django.db import models
class MyModel(models.Model):
file = models.FileField(upload_to='uploads/')
FileField
字段,用于用戶選擇要上傳的文件。from django import forms
class MyForm(forms.Form):
file = forms.FileField()
from django.shortcuts import render, redirect
from .forms import MyForm
def upload(request):
if request.method == 'POST':
form = MyForm(request.POST, request.FILES)
if form.is_valid():
my_model = MyModel(file=request.FILES['file'])
my_model.save()
return redirect('success')
else:
form = MyForm()
return render(request, 'upload.html', {'form': form})
upload.html
,用于顯示上傳文件的表單。<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
文件下載的步驟如下:
from django.db import models
from django.urls import reverse
class MyModel(models.Model):
file = models.FileField(upload_to='uploads/')
def get_download_url(self):
return reverse('download', args=[str(self.id)])
from django.http import FileResponse
from .models import MyModel
def download(request, pk):
my_model = MyModel.objects.get(pk=pk)
file_path = my_model.file.path
return FileResponse(open(file_path, 'rb'))
from django.urls import path
from .views import upload, download
urlpatterns = [
path('upload/', upload, name='upload'),
path('download/<int:pk>/', download, name='download'),
]
download.html
,用于顯示下載文件的鏈接。<a href="{{ my_model.get_download_url }}">Download</a>