Javascript 使用Flask和jQuery上传文件

Javascript 使用Flask和jQuery上传文件,javascript,jquery,python,html,ajax,Javascript,Jquery,Python,Html,Ajax,在jQuery中使用ajax调用编写发送html表单的程序时遇到问题。 这是我的upload.html和form.js文件: $(文档).ready(函数(){ $('form')。在('submit',函数(事件){ $.ajax({ 键入:“POST”, url:“/uploadhc”, 数据:$('hc') }) .完成(功能(数据){ if(data.error){ $('#errorAlert').text(data.error).show(); $('successAlert').

在jQuery中使用ajax调用编写发送html表单的程序时遇到问题。 这是我的upload.html和form.js文件:

$(文档).ready(函数(){
$('form')。在('submit',函数(事件){
$.ajax({
键入:“POST”,
url:“/uploadhc”,
数据:$('hc')
})
.完成(功能(数据){
if(data.error){
$('#errorAlert').text(data.error).show();
$('successAlert').hide();
}
否则{
$('#successAlert').text(data.file.show();
$('#errorAlert').hide();
}
});
event.preventDefault();
});
});

文件上传
请上传所有相应的文件

成功

失败


过去我这样做时,总是将
enctype=“multipart/form data”
放在
表单中

这里有几个链接可以更详细地解释它:


您需要以多部分上传的方式发送表单,您可以使用
FormData(formElement)

如果您有兴趣,这里有一个es6版本

//jquery(函数($){…})的缩写
//它与$(document).ready(function($)相等{
jQuery($=>{
$('form')。在('submit',event=>{
event.preventDefault()
let form=$('#upload hc')[0]
设fd=新表单数据(表单)
fetch('/uploadhc',{method'POST',body:fd})
。然后(res=>{
//console.log(res.ok)
返回res.json()//或res.text,res.arraybuffer
})
。然后(结果=>{
console.log(结果)
})
})
})
在html端:

<input type="file" id="uploadfile" name="NewCsvUpload">
在服务器端:

@app.route('/uploadLabel',methods=[ "GET",'POST'])
def uploadLabel():
    isthisFile=request.files.get('file')
    print(isthisFile)
    print(isthisFile.filename)
    isthisFile.save("./"+isthisFile.filename)

谢谢!我尝试了FormData([formElement]),但是ImmutableMultiDict([])仍然是空的。如果没有
[]
,您可以尝试吗?是的。但是我的服务器仍然无法获取表单数据。是的。但是我认为添加“enctype”在这里没有帮助。
var form_data = new FormData();
form_data.append('file', $('#uploadfile').prop('files')[0]);

$(function() {
$.ajax({
    type: 'POST',
    url:  '/uploadLabel',
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
        console.log('Success!');
    },
  })
});
@app.route('/uploadLabel',methods=[ "GET",'POST'])
def uploadLabel():
    isthisFile=request.files.get('file')
    print(isthisFile)
    print(isthisFile.filename)
    isthisFile.save("./"+isthisFile.filename)