这是我的代码:
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="file" name="myfile">
<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 %}
如何在Django项目中添加文件并将其保存在应用程序的媒体目录中?
答案 0 :(得分:1)
view.py
应该适合您!
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile) # saves the file to `media` folder
uploaded_file_url = fs.url(filename) # gets the url
return render(request, 'core/simple_upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'core/simple_upload.html')
答案 1 :(得分:0)
根据您是否尝试将文件上传到Model
或FileField
的{{1}},或者您只是想上传,会有轻微差异使用ImageField
类的服务器上不属于任何模型的文件。
请注意,Django有一个Form
类(Docs),可帮助您生成表单并通过验证处理Form
请求等。使用此类而不是编写自己的HTML代码。
POST
# forms.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
# views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})