<input id="file" type="file">可以实现选择文件;
var a=document.getElementById("file");
a.files[0];可以读取选择的文件
效果:
(红框部分,点击叉删除所选文件)
具体代码:
html:
<form enctype="multipart/form-data" method="post" action="">
<div class="itemlabel">
<label id="filelabel"><i class="fa fa-upload"></i>上传文件</label>
<input id="file" type="file" name="fileupload" style="display: none">
</div>
<div class="itemcontent">
<span id="fileinfo">未选择文件</span>
<i id="removefile" class="fa fa-remove"></i>
</div>
</form>
PS:这里将input隐藏,利用label代替input显示,从而修改样式(默认input样式有些无法修改),点击label时触发input点击
js
var uploadinput=document.getElementById("file");
$("#filelabel").click(function () {
$("#file").click();
});
uploadinput.addEventListener("change",function () {
if(uploadinput.files[0]){
var str=uploadinput.files[0].name;
console.log(str);
$("#fileinfo").text(str);
hasFile=1;
// uploadimg();//上传文件对接后台的具体操作
}
else{
console.log("未选择文件");
hasFile=0;
$("#fileinfo").text("未选择文件");
}
});
// function uploadimg() {
// if($("#file").files[0]){
// var formData = new FormData();
// formData.append('fileupload', $("#file").files[0]);
// $.ajax({
// url: ,
// type: "post",
// data: formData,
// processData: false,
// contentType: false,
// success: function (data) {
// console.log("success"+data);
// },
// error:function(err){
// console.log("error:"+err);
// }
// });
// }
// }
$("#removefile").click(function () {
uploadinput.value=null;
});
PS:
(1)清空已选择的文件:
var uploadinput=document.getElementById("file");
uploadinput.value=null;
(手动修改uploadinput.files=null或者=[]无效)
(2)选择文件时,提示内容动态更新:
uploadinput.addEventListener("change",function () {。。。});
(为input绑定change事件)