jquery->;django文件上传
是的,这是我如何将文件从jquery客户端上传到django服务器的又一个问题,除了在线找到的15个解决方案中没有一个适合我。(请原谅我的无知——我一般很少使用web框架) 因此,设置如下所示:jquery->;django文件上传,jquery,django,forms,Jquery,Django,Forms,是的,这是我如何将文件从jquery客户端上传到django服务器的又一个问题,除了在线找到的15个解决方案中没有一个适合我。(请原谅我的无知——我一般很少使用web框架) 因此,设置如下所示: 客户端: var formData = new FormData(); formData.append('file', response.output['file'], response.output['name']) $.ajax({ url: "djangourl
客户端:
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))
每次我尝试这个,我都会得到空的请求.FILES
,你知道为什么吗
更新:事实证明,request.POST包含绑定到“[object FileList]”(字面上是这个字符串)的键“file”,如果这有助于澄清情况的话。事实证明,我从前端(基于Aurelia的应用程序)收到的response.output['file']是一个FileList对象,而不是单个文件(虽然没有为
标记提供多个说明符)。结束主题,谢谢。我想您可能希望重用此问题中的一些代码:或此处