在Django中上传多个文件 [英] upload multiple files in django
本文介绍了在Django中上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是django的新手,我正尝试从浏览器上传多个文件并将它们存储在计算机存储中的某个位置,但是我无法使用此代码成功存储它们,请帮助我找出我的错误或改进之处可以做。预先感谢您的帮助。
I am new to django, I am trying to upload more than one file from the browser and store them somewhere in computer storage but I am not storing them successfully with this code please help me out to find my mistake or improvements that I can do. Thanks in advance to help.
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!")
app / 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" />
推荐答案
我要保存文档的模型
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
you can try a django create view in my code i use this 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>
这篇关于在Django中上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文