django实现文件上传
时间: 2023-11-29 20:05:50 浏览: 79
Django处理文件上传File Uploads的实例
在 Django 中,文件上传可以通过以下步骤实现:
1. 在模型中定义一个 FileField 字段,用于存储上传的文件信息,例如:
```
class Document(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
```
2. 在视图中处理文件上传请求,例如:
```
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
def upload(request):
if request.method == 'POST' and request.FILES['document']:
document = request.FILES['document']
fs = FileSystemStorage()
filename = fs.save(document.name, document)
uploaded_file_url = fs.url(filename)
return render(request, 'upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'upload.html')
```
3. 在模板中显示上传表单,例如:
```
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="document">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
{% endif %}
```
在这个示例中,上传的文件会被存储在指定目录中,同时在模板中会显示上传成功后的文件 URL。
阅读全文