简体   繁体   English

上传文件时将数据从javascript传递到Django视图

[英]passing data from javascript to django view when uploading a file

I created a no javascript code which uses an html form and django view to upload a file .It uses an html5 input element for selecting the file.On clicking the submit button,the file gets uploaded without any problem.The django view can get the file from request.FILES 我创建了一个no javascript代码的代码,该代码使用html formdjango view上传文件。它使用html5 input元素选择文件。单击submit按钮,文件就可以毫无问题地上传.django视图可以获取来自request.FILES文件

def upload_file(request,template_name):
    to_return = {}
    store_message="failure"
    if request.method == 'POST':
        if request.FILES.has_key('fselect'):
            file = request.FILES['fselect']
            with open('/uploadpath/%s' % file.name, 'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
            store_message="success"
    to_return['store_message']= store_message
    if store_message == "failure":
        return redirect('home')
    reqctx = RequestContext(request,to_return)
    return return render_to_response(template_name,reqctx)

the html form is html形式是

    <form enctype="multipart/form-data" method="post" action="{% url uploaded %}"> {% csrf_token %}
    <input type="file" name="fselect" id="fselect">    </input>
    <input type="submit" id="uploadbtn" value="upload">    
    </form>

Now I want to use some javascript to call the django view . 现在,我想使用一些javascript来调用django视图。 I have coded ajax version of upload view 我已编码ajax版本的上传视图

def ajax_upload_file(request):
    to_return = {}
    store_message="failure"
    if request.method == 'POST':
        if request.FILES.has_key('fselect'):
            file = request.FILES['fselect']
            with open('/uploadpath/%s' % file.name, 'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
            store_message="success"
     to_return['store_message']= store_message
     serialized = simplejson.dumps(to_return)
     if store_message == "failure":
        return HttpResponseServerError(serialized, mimetype="application/json")
     else:
        return HttpResponse(serialized, mimetype="application/json")

I am confused about how the file object can be passed from javascript code to django view. 我对如何将file对象从javascript代码传递到django视图感到困惑。

javascript code JavaScript代码

$(document).ready(function(){
  $('#fselect').change(function(){uploadFile()});

}
function uploadSubTitleFile(){
    //check if it is a subtitle file?
    var file=document.getElementById('fselect').files[0];
    var data = {  };//how to pass the data
    var args = { type:"POST", url:"ajax_upload/", data:data, complete:done };    
    return;
}

For the simple answer, you don't. 对于简单的答案,您不需要。 Send your form into an hidden iframe and and let the javascript call its parent window. 将您的表单发送到隐藏的iframe中,然后让javascript调用其父窗口。

Since file uploading occurs through an iframe, traditional response data such as HTTP status codes are not directly available, and connection manager cannot reasonably discern success or failure (except a transaction timeout). 由于文件上传是通过iframe进行的,因此传统的响应数据(例如HTTP状态代码)无法直接获得,并且连接管理器无法合理地识别成功或失败(事务超时除外)。 Instead, the callback's upload handler will receive a response object containing the body of the iframe document, as a string, when the transaction is complete. 取而代之的是,当交易完成时,回调的上载处理程序将以字符串形式接收包含iframe文档正文的响应对象。

http://developer.yahoo.com/yui/connection/#upload http://developer.yahoo.com/yui/connection/#upload

My advise is, find a decent library that does that for you and use it: 我的建议是,找到一个适合您的体面的图书馆并使用它:

With recent browsers, it's possible to do it without relying on an iframe: Sending multipart/formdata with jQuery.ajax 使用最新的浏览器,无需依赖iframe就可以做到这一点: 使用jQuery.ajax发送multipart / formdata

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM