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:執着

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章