zoukankan      html  css  js  c++  java
  • React 上传进度条问题 原生js上传 input type=“file”

    canUpload: true,//是否可以上传,初始值不可上传,所以disabled为true
    filename: '',//上传文件的名称 loading: false,//点击上传的时候出现加载图标 fileList: [],//已上传的文件列表 isNumber: true,//判断数量是否为数字,
    var file = document.getElementById("pic").files[0]; --------------------------------------------------------------------------------------------------------- //新的上传文件的js代码 submitUpload(){ if(!this.state.isNumber){ message.error("请输入正确的数字格式"); return } this.setState({ loading: true }); var here = this; var file=document.getElementById('pic').files[0]; // var decodeStr = URLDecoder.decode(this.state.datasetName); // decodeStr = this.state.datasetName; $.ajax({ // url: this.uploadUrl+"?name=" + URLDecoder.decode(this.state.datasetName), url: this.uploadUrl+"?name=" + this.state.datasetName, // url: ajax.shangchuanshu(decodeStr), type: "post", data: file, processData: false, contentType: false, success: function(res) { if(res){ if(res.status == "OK"){ here.uploadSuccess();//上传成功之后的操作 //延迟3秒刷新列表 setTimeout(function(){ here.getTrainDataSetList(); message.success("上传成功!"); var fileList = here.state.fileList; fileList.push(here.state.filename); here.setState({loading: false,fileList:fileList}); },2000); }else{ message.error(res.message); here.setState({loading: false}); } } }, error:function(err){ notification['error']({ message: here.state.filename+'文件上传失败', description: '' }); here.setState({loading: false}); } }); } --------------------------------------------------------------------------------------------------------- //判断文件选择框的值 fileInput(e){ var file=document.getElementById('pic').files[0]; var dataSetName=file.name.split(".zip")[0]; var filename = file.name; if(filename===''){ document.getElementById("fileTips").innerHTML="请选择要上传的文件"; }else{ document.getElementById("fileTips").innerHTML=""; var fileTypeArr = filename.split("."); var fileType = fileTypeArr[fileTypeArr.length-1]; } if(fileType!='zip'){ document.getElementById("fileTips").innerHTML="只能上传zip文件"; this.setState({canUpload: true,choiceFile:'请选择要上传的文件',datasetName:''});//当选择上传的文件不合法后,上传按钮的disabled为true }else{ this.getDatasetsName(file.name); if(!this.state.isNumber){ message.error("请输入正确的数字格式"); this.setState({ canUpload: true, datasetName:'', choiceFile:'请选择要上传的文件', });//当选择上传的文件合法后,上传按钮的disabled为false }else{ this.setState({ canUpload: false, choiceFile:filename, datasetName:dataSetName, filename: filename }); } } } --------------------------------------------------------------------------------------------------------- dataSetNumBlur(){ var regTest = /.*[^1-9]+.*$/;//是否存在除了数字之外的其他字符,为true,则不是数字 var isnum = regTest.test(this.state.datasetNum); if(isnum){ this.setState({isNumber: false});//上传按钮不可点击 document.getElementById("dataSetNum").innerHTML="请输入数字"; }else{ this.setState({isNumber: true}); document.getElementById("dataSetNum").innerHTML=""; } } --------------------------------------------------------------------------------------------------------- //新的上传文件的js代码 submitUpload() { this.setState({ loading: true, // listener: true }); var storage = window.sessionStorage; storage.setItem("listener", true) storage.setItem("first", true) // storage.setItem("timeout",6000) if (!this.state.isNumber) { message.error("请输入正确的数字格式"); return; } var here = this; var file = document.getElementById("pic").files[0]; var reg = /[u4e00-u9fa5]/; // var jqXHR; if (reg.test(file.name.split(".zip")[0]) == false) { here.setState({ progressBar: true }) //校验名称不能为汉字 here.state.jqXHR = $.ajax({ // url: this.uploadUrl+"?name=" + URLDecoder.decode(this.state.datasetName), url: this.uploadUrl + "?name=" + this.state.datasetName, type: "post", data: file, dataType: "json", processData: false, contentType: false, xhrFields: { withCredentials: true // 这里设置了withCredentials }, // timeout : this.state.timeout,//设置超时时间 // timeout : 6000, timeout: storage.getItem("timeout"), //--------------------------------------------{/*2222222 */} beforeSend: function () { notification['info']({ message: '提示', description: '现在开始上传文件!', }); }, xhr: function () { var storage = window.sessionStorage; if (storage.getItem("first") == "true") { if (here.state.myxhr.upload) { //上传数据时要判断是否有upload var storage = window.sessionStorage; // setTimeout (function(){ if (storage.getItem("listener") == "true") { // wi var heres = here; here.state.myxhr.upload.addEventListener('progress', heres.uploadssa.bind(heres), false); here.state.myxhr.upload.addEventListener('load', function (e) { }, false); } else { here.state.myxhr.upload.removeEventListener("progress", uploads, false) } // },2000); } else { } } else { } return here.state.myxhr; }, //-------------------------------------------- success: function (res) { if (res) { if (res.status == "OK") { here.uploadSuccess(); //上传成功之后的操作 //延迟3秒刷新列表 setTimeout(function () { message.success("上传成功!"); var fileList = here.state.fileList; fileList.push(here.state.filename); here.setState({ loading: false, fileList: fileList, // loading: true visible: false, uploadBtnssa: false }); here.getTrainDataSetList(); here.render(); }, 2000); } else { message.error(res.message); here.setState({ loading: false, visible: false }); here.getTrainDataSetList(); here.render(); } } }, error: function (err) { notification["error"]({ message: here.state.filename + "文件上传失败", description: "" }); here.setState({ loading: false }); // here.getTrainDataSetList(); here.render(); } }); } else { message.error("压缩包文件名中不能有汉字"); here.setState({ loading: false }); return; } } -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //判断文件选择框的值 fileInput(e) { //第二次点击 没走这个事件 var file = document.getElementById("pic").files[0]; var dataSetName = file.name.split(".zip")[0]; var filename = file.name; if (filename === "") { document.getElementById("fileTips").innerHTML = "请选择要上传的文件"; } else { document.getElementById("fileTips").innerHTML = ""; var fileTypeArr = filename.split("."); var fileType = fileTypeArr[fileTypeArr.length - 1]; } if (fileType != "zip") { document.getElementById("fileTips").innerHTML = "只能上传zip文件"; this.setState({ canUpload: true, choiceFile: "请选择要上传的文件", datasetName: "" }); //当选择上传的文件不合法后,上传按钮的disabled为true } else { this.getDatasetsName(file.name); if (!this.state.isNumber) { message.error("请输入正确的数字格式"); this.setState({ canUpload: true, datasetName: "", choiceFile: "请选择要上传的文件" }); //当选择上传的文件合法后,上传按钮的disabled为false } else { this.setState({ canUpload: false, choiceFile: filename, datasetName: dataSetName, filename: filename }); } } }

      

    用的antd progres进度条组件
    <Progress percent={this.state.percent} status = {this.state.percent< 100 ? "active": this.state.percent == 100 ? "success": "error"} showInfo={this.state.percent == 100 ? false : true} style ={{display: this.state.progressBar == true? "block": "none"}}/>
    ---------------------------------------------------------------------------------
    用的标签
    <input type="file" name="file" id="pic" onChange={this.fileInput.bind(this)} ref="referenceUpload"/>
    ---------------------------------------------------------------------------------
    获取上传的文件用
    document.getElementById("pic").files[0];
    ---------------------------------------------------------------------------------
    遇到的两个问题
    第1个问题 
    上传的时候 第2次点击同一个文件 不显示到页面上 input标签的onchange事件不执行
    
    解决
    $("#pic").replaceWith('<input type="file" name="file" className = "uploadssa" id="pic"/>');
            $("#pic").on("change", function () {
                _this.fileInput(_this)
            })
    
    replaceWith JQuery替换标签方法 替换掉页面原有的input标签 新标签可以跟旧input标签一样 事件得通过on事件添加才起效果
    
    附fileInput事件代码
    fileInput(e) {                                   //第二次点击 没走这个事件
            var file = document.getElementById("pic").files[0];
            var dataSetName = file.name.split(".zip")[0];
            var filename = file.name;
    
            if (filename === "") {
                document.getElementById("fileTips").innerHTML =
                    "请选择要上传的文件";
            } else {
                document.getElementById("fileTips").innerHTML = "";
                var fileTypeArr = filename.split(".");
                var fileType = fileTypeArr[fileTypeArr.length - 1];
            }
            if (fileType != "zip") {
                document.getElementById("fileTips").innerHTML = "只能上传zip文件";
                this.setState({
                    canUpload: true,
                    choiceFile: "请选择要上传的文件",
                    datasetName: ""
                }); //当选择上传的文件不合法后,上传按钮的disabled为true
            } else {
                this.getDatasetsName(file.name);
                if (!this.state.isNumber) {
                    message.error("请输入正确的数字格式");
                    this.setState({
                        canUpload: true,
                        datasetName: "",
                        choiceFile: "请选择要上传的文件"
                    }); //当选择上传的文件合法后,上传按钮的disabled为false
                } else {
                    this.setState({
                        canUpload: false,
                        choiceFile: filename,
                        datasetName: dataSetName,
                        filename: filename
                    });
                }
            }
    }
    ---------------------------------------------------------------------------------
    第2个问题
    xhr对象 删除事件监听 不能使用
    因为上传用的是xhr对象 这个对象有好几个自己的上传函数 有监听进度多少的(progress事件监听) 有监听完成的(load事件监听) 有监听超时的 这个xhr对象在jquery ajax里写的 直接停止ajax 就可以停止上传了 给jquery ajax赋值给一个全局变量 这样在其他方法里也能用这个ajax了 
    
    终止jquery ajax请求 用abort方法
    
    state: {
    myxhr: $.ajaxSettings.xhr()
    }
    
    here.state.myxhr.upload.addEventListener('progress', heres.uploadssa.bind(heres), false);
    
    here.state.myxhr.upload.addEventListener('load', function (e) {}, false);
    
    uploadssa(e) {
            if (e.lengthComputable) {
                let percent = Math.floor((e.loaded / e.total) * 100);
    
                let upload = this.state.upload;
                upload.progress.loaded = e.loaded;
                upload.progress.total = e.total;
                upload.progress.percentage = percent;
                this.state.upload = upload;
                this.setState({
                    upload: upload,
                    percent: percent
                });
            }
    } 终止ajax请求 就可以终止xhr对象的事件监听了 if (this.state.percent != null) {    this.state.jqXHR.abort(); }

      

  • 相关阅读:
    sharpen和filter2D
    Changing the contrast and brightness of an image!(opencv对比度和亮度调节)
    人脸表情识别
    Pycharm下载和安装
    Anaconda下载与安装
    图像人脸检测+人眼检测 (opencv + c++)
    cv2.VideoWriter()指定写入视频帧编码格式
    python_openCV例程遇到error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale的简单解决方法
    图像处理库 Pillow与PIL
    IDE bulid构建隐藏了什么(预处理->编译->汇编->链接)
  • 原文地址:https://www.cnblogs.com/zhanglanzuopin/p/12604362.html
Copyright © 2011-2022 走看看