2016-09-16 51 views
0

我是新來的django,我試圖從瀏覽器上傳多個文件,並將它們存儲在計算機存儲的某個地方,但我沒有用這段代碼成功地存儲它們,請幫我找到我的我可以做的錯誤或改進。預先感謝幫助。上傳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

你的天堂」沒有提到你的代碼有什麼問題,任何堆棧跟蹤或意外行爲都可以幫助調試它。 – SpiXel

+0

我沒有收到任何文件在我的存儲 –

+0

在我這裏給出的計算機存儲路徑/ Users/benq/djangogirls/upload/media/ –

回答

2

我的模型來保存文檔

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>