<div>
<input type="file" name="FileUpload" id="FileUpload" value="上传文件" />
<a onclick="uploadFile()">提交</a>
</div>
<script> //说明:上传文件必须为xls或xlsx格式
//input绑定change事件
var FileUpload = document.getElementById("FileUpload");
FileUpload.addEventListener("change",function(){
var name = FileUpload.files[0].name;
var i = name.lastIndexOf(".")
if(i>-1){
var ext = name.substring(i);
var index = [".xls",".xlsx"].indexOf(ext);
if(index==-1){
alert("文件格式错误")
FileUpload.value="";
}
}
}) //提交
uploadFile(){
var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
alert("请选择图片");
return;
}
var formFile = new FormData();
formFile.append("file", fileObj); //加入文件对象
$.ajax({
url: "",
data: formFile,
type: "Post",
dataType: "json",
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success: function (result) {
alert("上传完成!");
}
})
}
</script>