js上传文件,利用input type="file"选择文件及清空选择

17 篇文章 0 订阅

<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事件)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值