我在我的django項目中上傳文件時遇到問題。所以問題是:我如何通過jquery ajax將文件傳遞給django視圖?Django ajax jquery文件上傳
在這一刻我有
腳本:
<script type='text/javascript'>
$(document).ready(function() {
var csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
$('#upload').click(function() {
$.ajax({
csrfmiddlewaretoken: csrf_token,
type: 'POST',
url : '../ajax/upload_file/',
enctype: "multipart/form-data",
data : {
'file': $('#file').val()
},
success: function(data) {
console.log(data)
}
})
})
})
</script>
模板:
<form method="" action="" name='upload_form' id='upload_form' >{% csrf_token %}
<input type='file' name='file' id='file' />
<input type='button' value='Upload' id='upload'/>
</form>
和觀點:
@csrf_exempt
@xhr_to_json
def verifyFile(request):
if request.is_ajax():
file = request.FILES['file']
return {'message': file}
else:
return HttpResponseForbidden()
現在即時得到
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
return view_func(*args, **kwargs)
File "/home/vova/git/LV- 083_LAMP.git/Testcase_Project/Testcase_Project/views/decorator.py", line 6, in wrapper
data = func(*args, **kwargs)
File "/home/vova/git/LV- 083_LAMP.git/Testcase_Project/Testcase_Project/views/testcase.py", line 96, in verifyFile
request.FILES['file']
File "/usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py", line 258, in __getitem__
raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
MultiValueDictKeyError: "Key 'file' not found in <MultiValueDict: {}>"
是有可能做到這一點無需外部庫?
您是否嘗試過'文件= request.FILES.get( '文件')' – catherine 2013-04-04 12:33:45
返回對象{消息:空} – vovaminiof 2013-04-04 12:52:35
值傳遞 – vovaminiof 2013-04-04 12:59:33