我正在使用
XMLHttpRequest将文件从javascript代码发送到django视图.我需要检测,文件是否已发送,或者是否发生错误.我使用jquery写下列javascript.
理想情况下,我想向用户显示该文件未上传的错误消息.有什么方法可以在javascript中执行此操作吗?
我尝试通过从django视图返回成功/失败消息,将成功/失败的消息作为json并从django视图发送回序列化的json.为此,我使xhr.open()非异步.我试图打印xmlhttpRequest对象的responseText.console.log(xhr.responseText)显示
response= {"message": "success"}
我想知道的是,这是否是正确的方法.在许多文章中,我发现了这样的警告
Using async=false is not recommended
那么,有没有办法找出文件是否被发送,同时保持xhr.open()异步?
$(document).ready(function(){ $(document).on('change','#fselect',function(e){ e.preventDefault(); sendFile(); }); }); function sendFile(){ var form = $('#fileform').get(0); var formData = new FormData(form); var file = $('#fselect').get(0).files[0]; var xhr = new XMLHttpRequest(); formData.append('myfile',file); xhr.open('POST','uploadfile/',false); xhr.send(formData); console.log('response=',xhr.responseText); }
def store_uploaded_file(request): message='Failed' to_return = {} if (request.method == 'POST'): if request.FILES.has_key('myfile'): file = request.FILES['myfile'] with open('/uploadpath/%s' % file.name,'wb+') as dest: for chunk in file.chunks(): dest.write(chunk) message="success" to_return['message']= message serialized = simplejson.dumps(to_return) if store_message == "success": return HttpResponse(serialized,mimetype="application/json") else: return HttpResponseServerError(serialized,mimetype="application/json")
编辑:
我在@FabrícioMatté的帮助下得到了这个工作
xhr.onreadystatechange=function(){ if (xhr.readyState==4 && xhr.status==200){ console.log('xhr.readyState=',xhr.readyState); console.log('xhr.status=',xhr.status); console.log('response=',xhr.responseText); var data = $.parseJSON(xhr.responseText); var uploadResult = data['message'] console.log('uploadResult=',uploadResult); if (uploadResult=='failure'){ console.log('Failed to upload file'); displayError('Failed to upload'); }else if (uploadResult=='success'){ console.log('successfully uploaded file'); } } }
解决方法
XMLHttpRequest对象包含状态和readyState属性,您可以在xhr.onreadystatechange事件中测试,以检查您的请求是否成功.