2015-12-06 55 views
1

是的,這是一個更多的問題,我怎麼上傳文件從jquery客戶端到Django服務器,除了沒有約15個解決方案在網上找到工作。 (並且請原諒我的noobness--我一般都不經常使用web框架)。jquery - > django文件上傳

因此,設置是這樣的:
客戶端:

var formData = new FormData(); 
    formData.append('file', response.output['file'], response.output['name']) 
    $.ajax({ 
     url: "djangourl", 
     data: formData, 
     processData: false, 
     contentType: false, // also tried setting 'multipart/form-data', no profit 
     mimeType: 'multipart/form-data', 
     type: 'POST', 
     dataType: 'json', 
     cache: false, 
     success: function(data){ 
     alert(JSON.stringify(data)); 
     }, 
     error: function(data){ 
     alert(JSON.stringify(data)); 
     } 
    }); 

服務器端:

@require_http_methods(["POST"]) 
@csrf_exempt 
def upload_document(request, project_id): 
    try: 
     if request.FILES: 
      return HttpResponse(json.dumps("Yay!", default=json_util.default), status=200, content_type="application/json") 
     else: 
      return HttpResponse(json.dumps("Nah.", default=json_util.default), status=200, content_type="application/json") 
    except Exception as e: 
     return HttpResponseServerError(str(e)) 

每一次我嘗試這一次,我得到空request.FILES,任何想法,爲什麼?

更新:事實證明,request.POST包含綁定到「[object FileList]」(字面上這個字符串)的關鍵'文件',如果這有助於澄清情況。

+0

我想你可能想重用這個問題的一些代碼:http://stackoverflow.com/questions/19617996/file-upload-without-form –

+0

或在這裏http://stackoverflow.com/questions/166221 /何燦我上傳 - 文件 - 異步?RQ = 1 –

回答

1

事實證明,response.output [「文件」]其中我是從前端接收(基於奧裏利亞應用內)是文件列表對象,而不是單個文件(雖然沒有multiple指定符被給<input>標記)。閉幕話題,謝謝。