vov*_*iof 5 django ajax jquery file-upload django-views
我的django项目中的文件上传有问题.所以问题是:如何通过jquery ajax将文件传递给django视图?
这一刻我有
脚本:
<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>
Run Code Online (Sandbox Code Playgroud)
模板:
<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>
Run Code Online (Sandbox Code Playgroud)
并查看:
@csrf_exempt
@xhr_to_json
def verifyFile(request):
if request.is_ajax():
file = request.FILES['file']
return {'message': file}
else:
return HttpResponseForbidden()
Run Code Online (Sandbox Code Playgroud)
现在我得到了
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: {}>"
Run Code Online (Sandbox Code Playgroud)
没有外部库可以做到吗?
试试这个:
def upload(request):
id = request.POST['id']
path = '/var/www/pictures/%s' % id
f = request.FILES['picture']
destination = open(path, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
# return status to client
...
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读完整的教程:http://www.laurentluce.com/posts/upload-to-django-with-progress-bar-using-ajax-and-jquery/
| 归档时间: |
|
| 查看次数: |
8921 次 |
| 最近记录: |