gpt4 book ai didi

django ajax/jquery 文件上传

转载 作者:行者123 更新时间:2023-12-02 08:54:03 25 4
gpt4 key购买 nike

我正在尝试复制 Alex Kuhl 在他的优秀帖子中给出的示例:http://kuhlit.blogspot.com/2011/04/ajax-file-uploads-and-csrf-in-django-13.html

但是,我在复制这个方面并不太成功。

####### upload_page.html  

{% extends "base.html" %}
{% load i18n %}
{% block title %}Blog Post: Upload Files.{% endblock %}

{% block content %}
<div id="maintext">
<p>To upload a file, click on the button below.</p>
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
<script>
function createUploader(){
var uploader = new qq.FileUploader( {
action: "{% url ajax_upload %}",
element: $('#file-uploader')[0],
multiple: false,
onComplete: function( id, fileName, responseJSON ) {
if( responseJSON.success )
alert( "success!" ) ;
else
alert( "Sorry, your upload has failed! Please contact us by telephone or email." ) ;
},
onAllComplete: function( uploads ) {
// uploads is an array of maps
// the maps look like this: { file: FileObject, response: JSONServerResponse }
alert( "All complete!" ) ;
},
params: {
'csrf_token': '{{ csrf_token }}',
'csrf_name': 'csrfmiddlewaretoken',
'csrf_xname': 'X-CSRFToken',
},
} ) ;
}

// in your app create uploader as soon as the DOM is ready
// don't wait for the window to load
window.onload = createUploader;
</script>
</div>
{% endblock %}

views.py如下:

############### views.py
def upload_page( request ):
ctx = RequestContext( request, {
'csrf_token': get_token( request ),
})
return render_to_response( 'success/upload_page.html', ctx )

def save_upload( uploaded, filename, raw_data ):
filename = settings.UPLOAD_STORAGE_DIR
'''
raw_data: if True, uploaded is an HttpRequest object with the file being
the raw post data
if False, uploaded has been submitted via the basic form
submission and is a regular Django UploadedFile in request.FILES
'''
try:
from io import FileIO, BufferedWriter
with BufferedWriter( FileIO( filename, "wb" ) ) as dest:
# if the "advanced" upload, read directly from the HTTP request
# with the Django 1.3 functionality
if raw_data:
foo = uploaded.read( 1024 )
while foo:
dest.write( foo )
foo = uploaded.read( 1024 )
# if not raw, it was a form upload so read in the normal Django chunks fashion
else:
for c in uploaded.chunks( ):
dest.write( c )
# got through saving the upload, report success
return True
except IOError:
# could not open the file most likely
pass
return False

def ajax_upload( request ):
if request.method == "POST":
if request.is_ajax( ):
# the file is stored raw in the request
upload = request
is_raw = True
# AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload
try:
filename = request.GET[ 'qqfile' ]
except KeyError:
return HttpResponseBadRequest( "AJAX request not valid" )
# not an ajax upload, so it was the "basic" iframe version with submission via form
else:
is_raw = False
if len( request.FILES ) == 1:
upload = request.FILES.values( )[ 0 ]
else:
raise Http404( "Bad Upload" )
filename = upload.name

# save the file
success = save_upload( upload, filename, is_raw )

# let Ajax Upload know whether we saved it or not
import json
ret_json = { 'success': success, }
return HttpResponse( json.dumps( ret_json ) )

urls.py如下:

####### urls.py
urlpatterns = patterns('',
(r'media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
url(r'^$', index,name='home'),
url( r'^ajax_upload$', ajax_upload, name="ajax_upload" ),
url( r'^upload/$', upload_page, name="upload_page" ),
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('regfields.urls')),

# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),

# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),

代码也在:http://dpaste.com/600444/

虽然一切看起来都很好,但上传总是失败。

我使用:filename = settings.UPLOAD_STORAGE_DIR,其中,UPLOAD_STORAGE_DIR在settings.py中定义为“/media/”

谁能指出我哪里出错了(抱歉,我是网络编程新手,实际上以前从未使用过 JS,但可以合理地用 python 编程!)

最佳答案

您的 JavaScript 中有一个拼写错误。它应该读取 {% csrf_token %} 而不是 {{ csrf_token }}

编辑:在您发表评论后,我仔细查看了您链接的文章。

您需要包含库fileuploader.js。它将用带有适当事件处理程序的表单替换 id file-uploader 的占位符 div。用纯 HTML 创建表单将不起作用。

我建议您查看 Github 存储库中的示例:https://github.com/alexkuhl/file-uploader/tree/master/client

关于django ajax/jquery 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7145587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com