使用Python和Ajax Jquery上传文件
下面是我的html和jquery/ajax调用部分使用Python和Ajax Jquery上传文件,jquery,python,ajax,Jquery,Python,Ajax,下面是我的html和jquery/ajax调用部分 <form id="upload-file" role="form" action="sendQuestions" method="post" enctype="multipart/form-data"> <div class="modal-body"> <label for="file"><b>Upload packet here</b></label>
<form id="upload-file" role="form" action="sendQuestions" method="post" enctype="multipart/form-data">
<div class="modal-body">
<label for="file"><b>Upload packet here</b></label>
<input type="file" name="file">
<p class="help-block">Upload a .pdf or .docx file you want to read.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="upload-file-btn" type="button" class="btn btn-primary" data-dismiss="modal" value="Upload">Upload</button>
</div>
</form>
<script>
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: 'abc.py',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: false,
success: function(data) {
console.log('Success!');
},
});
});
});
现在,当我的ajax调用abc.py时,我得到了一个错误:
错误位于:
if fileitem.filename:
<type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'filename'
args = ("'NoneType' object has no attribute 'filename'",)
message = "'NoneType' object has no attribute 'filename'"
我理解,通过请求,我认为我们无法访问abc.py中的文件,如果我通过表单操作执行相同操作,我可以上载该文件。但在这个ajax调用中不是这样。请帮助如果输入字段是文件类型,则通过getvalue方法访问该值会将内存中的整个文件作为字符串读取。 相反,请使用“文件名”属性 form=cgi.FieldStorage
fileitem=form['file']属性是输入文件名看起来像你的表单。getvalue是方法,必须用brakets调用它:fileitem=form.getvalue'file'@Andrey Shokhin是的,这是一个明确的错误,我编辑了相同的代码。但是没有运气。非常感谢你的帮助。@好奇的家伙你能解决这个问题吗?
if fileitem.filename:
<type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'filename'
args = ("'NoneType' object has no attribute 'filename'",)
message = "'NoneType' object has no attribute 'filename'"