【问题标题】:django view cannot get file using request.FILES from ajax form submitdjango 视图无法使用 request.FILES 从 ajax 表单提交获取文件
【发布时间】:2012-06-06 09:43:05
【问题描述】:

我尝试使用 ajax 提交此表单,以便 django 视图可以从 request.FILES 中提取所选文件并写入服务器上的目录

<form enctype="multipart/form-data" method="post" id="fileupoadform">{% csrf_token %}
<p>
<label>Select a file
<input type="file" name="fselect" id="fselect"> </input>
</label>
</p>
<input type="submit" value="upload">
</form> 

视图是

def ajax_upload(request):
    print 'ajax_upload()'
    print 'request=',request
    to_return = {}
    store_message="failure"
    if (request.is_ajax()) and (request.method == 'POST'):
        print 'is ajax and post'
        print 'request.FILES=',request.FILES
        if request.FILES.has_key('fselect'):
            print "request has key='fselect'"
            file = request.FILES['fselect']
            with open(settings.UPLOADPATH'%s' % file.name, 'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
            store_message="success"
    to_return['store_message']= store_message
    print 'to_return=',to_return
    to_return['store_message']= store_message
    serialized = simplejson.dumps(to_return)
    print 'serialized=',serialized
    if store_message == "success":
        print 'suceessfully returning'
        return HttpResponse(serialized, mimetype="application/json")
    else:
        print 'failed!! returning'
        return HttpResponseServerError(serialized, mimetype="application/json")

我用jquery来提交ajax

$(document).ready(function(){
    $('#fileupoadform').submit(function(e){
        submitUploadForm(e);            
    });
});
function submitUploadForm(e){
    console.log('clicked submit');
    e.preventDefault(); 
    var file = $('#fselect').get(0).files[0];
    console.log('filename='+file.name)  
    var data = { name:file.name };
    var args = { type:"POST", url:"upload/", data:data, complete:doneAjaxUpload };  
    $.ajax(args);   
}

当我尝试这个时,我得到了这个控制台输出

ajax_store_uploaded_file()
request= <WSGIRequest
GET:<QueryDict: {}>,
POST:<QueryDict: {u'name': [u'myfile.srt']}>,
COOKIES:{'csrftoken': 'ca367878345fa9e59adf79hg047a1dvb'},
...
is ajax and post
request.FILES= <MultiValueDict: {}>
to_return= {'store_message': 'failure'}
serialized= {"store_message": "failure"}
failed!! returning
[01/Jun/2012 11:27:26] "POST /myapp/upload/ HTTP/1.1" 500 28

我感觉我在 django 视图中做错了什么。是我无法从request.FILES 获取上传的文件吗?在django viewnon ajax version 中,我能够从请求中获取文件.FILES 使用request.FILES['fselect']

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你用哪个js库帮助上传?
  • @okm ,只有 jquery 和上面的脚本

标签: javascript ajax django file-upload


【解决方案1】:

我认为你不能(轻松地)上传 ajax 文件。

当然,看起来您实际上并没有将文件传递给您的帖子数据,您只是传递了文件名 -

var data = { name:file.name };

查看此问题以获取插件/信息以帮助执行此操作 - How can I upload files asynchronously?

【讨论】:

  • data 仅用于测试目的。普通表单提交在 request.FILES 中有文件数据,为什么通过 ajax 完成提交时,它丢失了?
  • 我认为你需要展示“提交是如何通过 ajax 完成的”。该文件不在 request.FILES 中的事实表明,损坏的是 javascript,而不是 django。实际提交文件的代码是什么?
  • 感谢@Aidan 的回复..最后我通过使用formDataXMLHttpRequest.send 得到了这个工作..
猜你喜欢
  • 2012-03-14
  • 2018-05-31
  • 2021-09-30
  • 2020-11-24
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
相关资源
最近更新 更多