2011-04-21 59 views

回答

9

request.FILES.get('filename', None)響應一個表單指定字段的存在是這樣的:

<input type="file" name="filename"></input> 

如果你有兩個這樣的領域:

<input type="file" name="file1"></input> 
<input type="file" name="file2"></input> 

然後request.FILES.get('file1', None)request.FILES.get('file2', None)應該分別給你的那些文件。

原因是多部分MIME。應該上傳三個部分(表單數據,file1,file2),Django的UploadFileHandler分別將其拆分爲request.POSTrequest.FILES

+0

它不工作,我這樣做就像這樣。 'newsform = NewsAddForm(request.POST or None,request.FILES.get('image_news1',None),request.FILES.get('image_news2',None))' – Aryan 2016-09-23 05:51:24

29

我遲到了,但我一直試圖弄清楚這一點,終於有了一個解決方案。 查看此處使用的代碼:https://code.djangoproject.com/ticket/12446

您可以使用getlist訪問多部分值。如果我的HTML的形式是:

<form enctype="multipart/form-data" action="" method="post"> 
<input type="file" name="myfiles" multiple> 
<input type="submit" name="upload" value="Upload"> 
</form> 

我的Django代碼來處理它看起來像:

for afile in request.FILES.getlist('myfiles'): 
    # do something with afile 

寫一個表單字段/小工具來處理這個正確的是我的下一個步驟。我對使用Django還比較陌生,所以我正在學習。

+0

你是怎麼做到的?你能舉個例子嗎?我希望藝術家用戶以同一形式同時上傳多個文件。 – 2014-07-25 06:10:29

0

這是這個答案的好鏈接:https://github.com/Chive/django-multiupload。但是,由於我沒有使用ModelForm,所以我不得不做一些改變。 鑑於我寫下面的代碼和保存的文件到磁盤:

for each in form.cleaned_data['attachments']: 
    handle_uploaded_file(each) 

def uploadMyWork(request): 
    from .forms import UploadFileForm, handle_uploaded_file 
    print 'in uploadMyWork' 

    if request.method == 'GET': 
     print 'in uploadMyWork : GET' 
     form = UploadFileForm() 
    else: 
     form = UploadFileForm(request.POST, request.FILES) 
     print 'in uploadMyWork : POST' 
     #for each in form.cleaned_data['attachments']: 
     # handle_uploaded_file(each) 
     #return render(request, 'stitchme/uploadMyWork.html', {'msg': "file uploaded successfully"}) 

     if form.is_valid(): 
      print 'inside form valid' 
      for each in form.cleaned_data['attachments']: 
       handle_uploaded_file(each) 
      return render(request, 'stitchme/uploadMyWork.html', {'msg': "file uploaded successfully"}) 

    print 'returning to uploadmywork' 
    return render(request, 'stitchme/uploadMyWork.html', {'form': form, 'msg':'hi'}) 
相關問題