Django文件上传下载
时间: 2024-02-04 15:08:51 浏览: 78
以下是Django文件上传下载的步骤:
1. 创建Django项目和应用程序:
```shell
django-admin startproject file_upload
cd file_upload
python manage.py startapp uploader
```
2. 配置URL路由:
在项目的urls.py文件中,添加以下代码:
```python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('uploader/', include('uploader.urls'))
]
```
3. 创建文件上传表单:
在应用程序的forms.py文件中,创建一个文件上传表单:
```python
from django import forms
class FileUploadForm(forms.Form):
file = forms.FileField()
```
4. 创建文件上传视图:
在应用程序的views.py文件中,创建一个文件上传视图:
```python
from django.shortcuts import render
from .forms import FileUploadForm
def upload_file(request):
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
file = form.cleaned_data['file']
# 处理文件上传逻辑
# 保存文件到服务器或者其他操作
return render(request, 'success.html')
else:
form = FileUploadForm()
return render(request, 'upload.html', {'form': form})
```
5. 创建文件上传模板:
在应用程序的templates文件夹中,创建upload.html模板文件:
```html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">上传</button>
</form>
```
6. 创建文件上传成功模板:
在应用程序的templates文件夹中,创建success.html模板文件:
```html
<h1>文件上传成功!</h1>
```
7. 配置文件上传URL:
在应用程序的urls.py文件中,添加以下代码:
```python
from django.urls import path
from .views import upload_file
urlpatterns = [
path('upload/', upload_file, name='upload'),
]
```
现在,您可以通过访问`http://localhost:8000/uploader/upload/`来上传文件。
阅读全文