文件上传使用Django [英] FileUpload with Django
问题描述
我使用的是 AJAX上传 code做了一个简单的AJAX文件上传。我来跨越的问题是,该文件没有显示在后台提交后。
前端code是pretty的基础:
< DIV ID =image_uploader>上传更多图片< / DIV>
<脚本类型=文/ JavaScript的字符集=utf-8>
功能createUploader(){
VAR上传=新qq.FileUploader({
元素:的document.getElementById('image_uploader),
动作:/添加/图像/ 1',
调试:真实,
的onsubmit:函数(){
progress.show();
},
的onComplete:函数(){
progress.hide();
},
OnCancel的:函数(){
progress.hide();
},
});
};
createUploader();
< / SCRIPT>
后端code(目前正在进行中)也pretty的基础:
高清add_image(请求ID):
打印请求
如果request.FILES:
返回的Htt presponse({成功:真})
其他:
返回的Htt presponse({成功:假消息:找不到FILES})
对于我来说,使用code从的亚历克斯·库尔, request.GET中['qqfile']
有文件名和 request.read()
(在Django 1.3)返回的数据。
request.FILES只适用于尚未没有发生对我来说,一个场景。我使用AJAX上传直接对话Photologue,和我的code看起来是这样的:
高清save_upload(上传,文件名,raw_data):
raw_data:如果为真,upfile是生后数据的Htt prequest对象
作为文件,而不是一个Django UploadedFile的从request.FILES
尝试:
文件名= os.path.normpath(os.path.join(IMAGE_UPLOAD_PATH,文件名))
使用的BufferedWriter(FileIO专注(文件名,世行))为DEST:
#如果先进的上传,直接从HTTP请求读取
#与Django的1.3功能
如果raw_data:
(目录名,文件名)= os.path.split这样的(文件名)
(fileBaseName,fileExtension)= os.path.splitext(文件名)
#
#在这里,如果fileBaseName小于n个字符,可能要就打上只是为了好玩日期
#
尝试:
i_can_has_p = Photo.objects.get(标题= fileBaseName)
标题= fileBaseName +_+ STR(datetime.datetime.now()的strftime(%Y%M%胸苷%H%M%S))
除了Photo.DoesNotExist:
标题= fileBaseName
title_slug = slugify(标题)
P =照片(标题=标题,title_slug = title_slug)
p.image.save(文件名,ContentFile(uploaded.read()))
#如果不生,这是一个形式上传,以便读取普通的Django豆腐块时尚
其他:
#TODO:弄清楚这个时候被调用,使其工作保存成图片如上
对于C在uploaded.chunks():
dest.write(三)
除了IO错误:
#无法最有可能打开文件
返回False
返回True
高清ajax_upload(要求):
如果request.method ==POST:
#AJAX上传将通过在查询字符串的文件名,如果它是高级AJAX上传
如果request.is_ajax():
#该文件被存储的原始的请求
上传=请求
is_raw = TRUE
尝试:
文件名= request.GET中['qqfile']
除了KeyError异常:
返回的Htt presponseBadRequest(AJAX请求无效)
#不是一个ajax上传,于是就出现了基本的iframe版本通过表单提交
其他:
is_raw =假
如果len(request.FILES)== 1:
#FILES是在Django一本字典,而是阿贾克斯上传给了上传文件的
#的ID的基础上随机数,所以它在这里不能猜测在code。
#而不是编辑阿贾克斯上传来传递ID的查询字符串,请注意
#每次上传的一个单独的请求,以便文件应该只有一个入口。
#因此,我们可以只抢到第一(也是唯一一个)在字典的价值。
上传= request.FILES.values()[0]
其他:
提高HTTP404(坏上传)
文件名= upload.name
#保存文件
成功= save_upload(上传,文件名,is_raw)
#让阿贾克斯上传知道我们是否保存与否
ret_json = {成功:成功,}
返回的Htt presponse(json.dumps(ret_json))
在我的情况下, ajax_upload
是称为AJAX的动作的功能:
参数
I'm using the ajax-upload code to do a simple AJAX file upload. The issue I'm coming across is the file isn't showing up on the backend after submitting.
The frontend code is pretty basic:
<div id="image_uploader">Upload More Images</div>
<script type="text/javascript" charset="utf-8">
function createUploader(){
var uploader = new qq.FileUploader({
element: document.getElementById('image_uploader'),
action: '/add/image/1',
debug: true,
onSubmit : function () {
progress.show();
},
onComplete : function () {
progress.hide();
},
onCancel : function () {
progress.hide();
},
});
};
createUploader();
</script>
The backend code (currently in progress) is also pretty basic:
def add_image(request, id):
print request
if request.FILES:
return HttpResponse("{success:true}")
else:
return HttpResponse("{success:false, message:'Unable to find FILES}")
For me, using code from Alex Kuhl, request.GET['qqfile']
had the filename and request.read()
(in Django 1.3) returned the data.
request.FILES was only used in a scenario that hasn't yet happened for me. I'm using ajax-upload to talk directly to Photologue, and my code looks something like this:
def save_upload( uploaded, filename, raw_data ):
"""
raw_data: if True, upfile is a HttpRequest object with raw post data
as the file, rather than a Django UploadedFile from request.FILES
"""
try:
filename = os.path.normpath(os.path.join(IMAGE_UPLOAD_PATH, filename))
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:
(dirName, fileName) = os.path.split(filename)
(fileBaseName, fileExtension)=os.path.splitext(fileName)
#
# right here, if fileBaseName is less than n characters, might want to slap on a date just for fun
#
try:
i_can_has_p = Photo.objects.get(title=fileBaseName)
title = fileBaseName + "_" + str(datetime.datetime.now().strftime("%Y%m%dT%H%M%S"))
except Photo.DoesNotExist:
title = fileBaseName
title_slug = slugify(title)
p = Photo(title=title, title_slug=title_slug)
p.image.save(filename,ContentFile(uploaded.read()))
# if not raw, it was a form upload so read in the normal Django chunks fashion
else:
# TODO: figure out when this gets called, make it work to save into a Photo like above
for c in uploaded.chunks( ):
dest.write( c )
except IOError:
# could not open the file most likely
return False
return True
def ajax_upload( request ):
if request.method == "POST":
# AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload
if request.is_ajax( ):
# the file is stored raw in the request
upload = request
is_raw = True
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:
# FILES is a dictionary in Django but Ajax Upload gives the uploaded file an
# ID based on a random number, so it cannot be guessed here in the code.
# Rather than editing Ajax Upload to pass the ID in the querystring, note that
# each upload is a separate request so FILES should only have one entry.
# Thus, we can just grab the first (and only) value in the dict.
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
ret_json = { 'success': success, }
return HttpResponse( json.dumps( ret_json ) )
In my case, ajax_upload
is the function called by ajax's action:
parameter
这篇关于文件上传使用Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!