react学习--上传文件

用原生的js的话大概就是

  <input type="file" id="tp" name="tp"/>
   <buttonοnclick="xxx()"></button>
function xxx(){
var f = document.getElementByIdx_x_x_x_x("tp").files[0];
    var reader = newFileReader();
    reader.onload = function(e) {
       var data = e.target.result;
       //加载图片获取图片真实宽度和高度
       var image = new Image();
       image.οnlοad=function(){
           var width= image.width;
           var height= image.height;
           ;
       };
       image.src= data;
   };
  reader.readAsDataURL(f);
}

不过呢,react建立在这个基础上,原理是一样的

fileInput = React.createRef();
<input type='file' ref={this.fileInput} onChange={this.handleFileChange} />

ref则直接控制input,用其他控件来激活input的onClick`

	/**激活input的点击事件**/
    handleClickPicture = (e) => {
    	//点击之后就会弹出本地文件系统
        this.fileInput.current.click()
    }

然后只要选择了文件,input上的change事件就会触发

    /**
     * 处理文件改变
     */
    handleFileChange = (e) => {
        //e.target.files[0];
        const file = e.target.files[0];
        const reader = new FileReader();
        const {userInfo} = this.state;
        const AllowImgFileSize = 2100000; //上传图片最大值(单位字节)( 2 M = 2097152 B )超过2M上传失败
        if (file) {
            //将文件以Data URL形式读入页面
            let imgUrlBase64 = reader.readAsDataURL(file);
            reader.onload =  (e)=> {
                //var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分(可选可不选,需要与后台沟通)
                if (AllowImgFileSize != 0 && AllowImgFileSize < reader.result.length) {
                    alert( '上传失败,请上传不大于2M的图片!');
                    return;
                }else{
                    alert(reader.result);
                    //执行上传操作
                    userInfo.picture = reader.result;
                    this.setState({userInfo})

                }
            }
        }
    }

上述操作是把图片转成base64然后把结果回显到指定容器内,也可以上传到后台服务器,返回一个图片远程连接,然后回显

好了,react对于文件操作完成
–by:执着

发布了34 篇原创文章 · 获赞 6 · 访问量 3653

猜你喜欢

转载自blog.csdn.net/qq_35986709/article/details/102560904