JS的文件上传方法,点击确认按钮后上传文件,点击取消放弃上传。
方法如下:
function upload(){
var fileName = $("#filename")[0].innerHTML; //获取文件名
var ext = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length).toLowerCase();
if (ext == 'txt') { //判断文件类型
swal({
icon: "warning",
title: [[#{confirmUpload}]], //thymeleaf取国际化文件中的值
text: [[#{cannotdeleteimort}]],
buttons:{
cancel: { //取消按钮
text: [[#{cancel}]],
value: null,
visible: true
},
confirm: { //确认按钮
text: [[#{comfirm}]],
value: true,
visible: true
}
}
}).then(function(isOk){ //判断是否点击确认
if(!isOk) //如果点击取消
swal.close();
else{
$("#uploadForm").ajaxSubmit({ //点击确认
type: "post",
url:'/xxx/xxx',
data: $("#uploadForm").serialize(),
dataType: "text",
cache: false,
beforeSend: function(){
swal({
icon: "info",
text:[[#{importing}]]
});
},
complete: function(){
swal.close();
},
error : function(textStatus, errorThrown) {
swal({
icon: "error",
text:[[#{importFail}]]+textStatus
});
},
success: function(data){
if(data=="x")
swal([[#{x}]]);
else
swal(data);
}
});
}
});
}else{//上傳文件應該是.txt
swal({
icon: "error",
text:[[#{txtfile}]]
});
}
}