React 頭像插件 react-avatar-editor 的使用

前端源碼:css

  • 建議配合 圖像壓縮插件使用, 壓縮後再對imageOrigin賦值操做,否則會很卡。
  • 推薦使用這個插件, zhuanlan.zhihu.com/p/38006124
  • 該插件使用異步方法獲取到壓縮後的圖片的blob對象, blob轉base64url很容易
var reader = new window.FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function(e) {
               var base64data = e.target.result;                
               console.log( base64data );
 }
複製代碼
  • 個人雙核I7處理器在加上了移動觸發事件和調節range後巨卡無比。
  • 所以使用的小圖片測試
import React, { Component } from 'react';
import './App.css';

// 這個就是頭像插件
import ReactAvatarEditor from 'react-avatar-editor';
//使用axios發給後端作一下測試
import axios from 'axios'



class App extends Component {

  state = {
    range: 12,
    imageOrigin: "",
    imageResult: "",
    readerOrigin: new FileReader()
  }
    
    // 組件自帶的獲取結果事件
  onClickSave = () => {
    //獲取 base64url格式結果
    const canvas = this.editor.getImage().toDataURL();
    //能夠將這段base64url 字符串傳給後端

    //顯示結果 blob 對象
    fetch(canvas)
      .then(res => res.blob())
      .then(blob => {
        this.img = window.URL.createObjectURL(blob)
        this.setState({ imageResult: this.img })
      })
  }
    
    // 從本機獲取圖片
  changeFile(e) {
    var file = e.target.files[0];
    this.state.readerOrigin.readAsDataURL(file);
    this.state.readerOrigin.onload = (e) => {
      this.setState({
        imageOrigin: e.target.result,
      });
    }
  }
 
  //圖片上傳到服務器
  onUpload() {
  //能夠將這段base64url 字符串傳給後端
    const canvas = this.editor.getImage().toDataURL();
    let params = new URLSearchParams();
    params.append('avatar', canvas);
    axios({
      method:"post",
      url:"http://localhost:12306/",
      data:params
    }).then(res=>{
        //alert('上傳成功')
    }).catch(err=>{
        //alert('圖片過大, 請使用小圖片')
    })
  }
  
  
  render() {
    return (
      <div className="App">
        //輸入頭像位置
        <input type="file" onChange={(e) => { this.changeFile(e) }} />
        
        //組件位置
        <ReactAvatarEditor
          ref={(node) => {
            this.editor = node;
          }}
          image={this.state.imageOrigin}
          width={200}
          height={200}
          border={50}
          borderRadius={125}
          color={[255, 255, 255, 0.6]} // RGBA
          //圖片被放大的比例 (高度)
          scale={1 + this.state.range / 100}
          rotate={0}
          onMouseMove={(e) => {
            this.onClickSave()
          }}
        ></ReactAvatarEditor>
        <input type="range" onChange={(e) => {
          this.onClickSave()
          this.setState({ range: e.target.value })
        }}></input>
        <button onClick={
          () => this.onClickSave()
        }>查看頭像</button>
        <button onClick={
          () => this.onUpload()
        }>確認上傳</button>
        
        
        //圖片查看區域
        <div style={{ width: "200px", height: "200px", border: "1px solid black" }}>
          <img style={{ width: "100%", height: "100%" }} src={this.state.imageResult} alt="" />
        </div> 

      </div>
    );
  }
}

export default App;

複製代碼

後段測試源碼:前端

const express = require('express');
const server = express();
const bodyParser = require('body-parser');

server.use(bodyParser({limit: '0.5mb'}));
server.listen(12306);
server.use('/' , (req,res)=>{
    res.setHeader('Access-Control-Allow-Origin','*')
    console.log(req.body)
})
複製代碼

待續...node

相關文章
相關標籤/搜索