A-A+
如何使用button实现ajax上传文件?
有的时候input的file文件框样式比较丑,所以我们会默认隐藏起来,使用button来实现文件上传。
直接贴代码,备注下。
html代码:
<form id="infoLogoForm" enctype='multipart/form-data'>
<a class="btn btn-blue" href="/static/template.xlsx" data-icon="arrow-down">下载模板</a>
<button type="button" class="btn btn-blue" data-icon="sign-in" id="import">导入商户</button>
<input type="file" accept=".xls,.xlsx" style="display: none;" id="file_import" name="file">
</form>
js代码:
$("#import").click(function () {
return $("#file_import").click();
});
var uploading = false;
$("#file_import").on("change", function(){
if(uploading){
alert("文件正在上传中,请稍候");
return false;
}
var fileName = $(this).val(); //获得文件名称
var fileType = fileName.substr(fileName.length-4,fileName.length); //截取文件类型,如(.xls)
//console.log(fileType);
if(fileType == 'xlsx' || fileType == 'xls')
{
$.ajax({
url: "/upload/excel",
type: 'POST',
cache: false,
data: new FormData($('#infoLogoForm')[0]),
processData: false,
contentType: false,
dataType:"json",
beforeSend: function(){
uploading = true;
},
success : function(data) {
if (data.status == 200) {
alert('上传成功')
} else {
}
uploading = false;
}
});
}
else
{
alert('上传文件类型错误,支持类型: .xls .xlsx');
}
});