我是django的新手,我正在尝试从浏览器上传多个文件并将它们存储在计算机存储中的某个位置,但我没有成功存储它们,请使用此代码帮助我找出我的错误或改进我可以做。在此先感谢您的帮助。
views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def Form(request):
return render(request, "index/form.html", {})
def Upload(request):
for count, x in enumerate(request.FILES.getlist("files")):
def process(f):
with open('/Users/benq/djangogirls/upload/media/file_' + str(count), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
process(x)
return HttpResponse("File(s) uploaded!")
应用/ urls.py
from django.conf.urls import url
from index import views
urlpatterns = [
url(r'^form/$', views.Form),
url(r'^upload/$', views.Upload)
]
form.html
<form method="post" action="../upload/" entype="multipart/form-data"> {% csrf_token %}
<input type="file" name="files" multiple />
<input type="submit" value="Upload" />
答案 0 :(得分:6)
我保存文档的模型
class Document(models.Model):
file = models.FileField('Document', upload_to='mydocs/')
@property
def filename(self):
name = self.file.name.split("/")[1].replace('_',' ').replace('-',' ')
return name
def get_absolute_url(self):
return reverse('myapp:document-detail', kwargs={'pk': self.pk})
你可以在我的代码中尝试django创建视图我使用这个DocumentCreateView
class DocumentCreate(CreateView):
model = Document
fields = ['file']
def form_valid(self, form):
obj = form.save(commit=False)
if self.request.FILES:
for f in self.request.FILES.getlist('file'):
obj = self.model.objects.create(file=f)
return super(DocumentCreate, self).form_valid(form)
我的表单html文件
<script>
$(document).ready(function(){
$('#id_file').attr("multiple","true");
})
</script>
<form method="post" enctype="multipart/form-data" action="">{% csrf_token %}
{{ form.file }}
<input type="submit" value="upload" />
</form>
答案 1 :(得分:0)
我能够在Django Class based UpdateView with Form for Multiple Uploaded Files的create视图中解决“多次上传”部分,但是,现在更新get函数是我目前所坚持的。
答案 2 :(得分:0)
django官方文档的答案
file_field = Forms.FileField(widget = forms.ClearableFileInput(attrs = {'multiple':True}))
https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/#uploading-multiple-files
答案 3 :(得分:0)
views.py
BadRequest()
urls.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def Form(request):
for x in request.FILES.getlist("files"):
def process(f):
with open('/Users/benq/djangogirls/upload/media/file_' + str(x), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
process(x)
return render(request, "index/form.html", {})
为我工作。