在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>