FileManageMobileWx.js 19.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
/* eslint-disable */
/* eslint-disable prefer-destructuring */
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react';
import { Button, Toast } from 'antd-mobile-v2';
import 'antd-mobile-v2/dist/antd-mobile.css';
import weixin from 'weixin-js-sdk';
import logo from '@/assets/footer_logo.png';
import * as commonUtils from '../../utils/utils';
import CommobileClassifyEvent from '../common/CommobileClassifyEvent';
import CommobileBase from '../common/CommobileBase';
import  commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import preView from '../components/preView';
import styles from './fileManage.less';


class FileManageMobile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      files: [], // 图片存放的数组 可以上传一个,或者多个图片
      imageData: [],
    };
  }

  /* 调用手机摄像头并拍照 */
   getImage =() => {
     const { plus } = window;
     const cmr = plus.camera.getCamera();
     cmr.captureImage((p) => {
       plus.io.resolveLocalFileSystemURL(p, (entry) => {
         this.startUpload(entry.toLocalURL(), entry.name);
       }, (e) => {
         plus.nativeUI.toast(`读取拍照文件错误:${e.message}`);
       });
     }, (e) => {
       plus.nativeUI.toast(`调用摄像头错误:${e.message}`);
     }, {
       filter: 'image',
     });
   }

  /* 相册选择图片 */
   getPhoto =() => {
     const { plus } = window;
     plus.gallery.pick((path) => {
       const name = path.substring(path.lastIndexOf('/') + 1);
       this.startUpload(path, name);
     }, (e) => {
       plus.nativeUI.toast(`选取图片错误:${e.message}`);
     }, { filter: 'image' });
   }

  showImgDetail = (imgId, imgkey, id, src) => {
    let html = '';
    html += `<div  id="Img${imgId}${imgkey}" class="image-item ">`;
    html += `   <img id="picBig" data-preview-src="" data-preview-group="1" ${src}  />`;
    html += `    <span class="del" onclick="delImg('${imgId}','${imgkey}',${id});">`;
    html += '        <div class="fa fa-times-circle"></div>';
    html += '    </span>';
    html += '</div>';
    document.getElementById('imgDiv').innerHTML = html;
  }

  // 压缩图片
  compressImage =(url, filename, divid) => {
    const { plus } = window;
    const name = `_doc/upload/${divid}-${filename}`;// _doc/upload/F_ZDDZZ-1467602809090.jpg
    plus.zip.compressImage(
      {
        src: url, // src: (String 类型 )压缩转换原始图片的路径
        dst: name, // 压缩转换目标图片的路径
        quality: 20, // quality: (Number 类型 )压缩图片的质量.取值范围为1-100
        overwrite: true, // overwrite: (Boolean 类型 )覆盖生成新文件
      },
      (event) => {
      // uploadf(event.target,divid);
        const path = name;// 压缩转换目标图片的路径
        // event.target获取压缩转换后的图片url路
        // filename图片名称
        this.saveimage(event.target, divid, filename, path);
      }, (error) => {
        plus.nativeUI.toast(`${error}压缩图片失败,请稍候再试`);
      },
    );
  }


  // 保存信息到本地
  /**
   *
   * @param {Object} url  图片的地址
   * @param {Object} divid  字段的名称
   * @param {Object} name   图片的名称
   */
   saveimage = (url, divid, name, path) => {
     const { plus } = window;
     // alert(url);//file:///storage/emulated/0/Android/data/io.dcloud...../doc/upload/F_ZDDZZ-1467602809090.jpg
     // alert(path);//_doc/upload/F_ZDDZZ-1467602809090.jpg
     // const state = 0;
     const wt = plus.nativeUI.showWaiting();
     //  plus.storage.clear();
     name = name.substring(0, name.indexOf('.'));// 图片名称:1467602809090
     const id = document.getElementById('ckjl.id').value;
     const itemname = `${id}img-${divid}`;// 429img-F_ZDDZ
     let itemvalue = plus.storage.getItem(itemname);
     if (itemvalue == null) {
       itemvalue = `{${name},${path},${url}}`;// {IMG_20160704_112614,_doc/upload/F_ZDDZZ-IMG_20160704_112614.jpg,file:///storage/emulated/0/Android/data/io.dcloud...../doc/upload/F_ZDDZZ-1467602809090.jpg}
     } else {
       itemvalue = `${itemvalue}{${name},${path},${url}}`;
     }
     plus.storage.setItem(itemname, itemvalue);

     const src = `src="${url}"`;
     this.showImgDetail(name, divid, id, src);
     wt.close();
   }

  // 上传图片
  //  upload_img = (p) => {
  //    // 又初始化了一下文件数组 为了支持单个上传,如果你要一次上传多个,就不要在写这一行了
  //    // 注意
  //    // files=[];
  //    const n = p.substr(p.lastIndexOf('/') + 1);
  //    files.push({
  //      name: `name${files.length}`,
  //      path: p,
  //    });
  //  }

   startUpload =(path, filename) => {
     const { files } = this.state;
     const { sModelsId, token } = this.props;
     const { plus } = window;
     // if (files.length <= 0) {
     //   plus.nativeUI.alert('没有添加上传文件!');
     //   return;
     // }

     // 原生的转圈等待框
     const wt = plus.nativeUI.showWaiting();

     const task = plus.uploader.createUpload(
       `${commonConfig.file_host}file/mobileupload?sModelsId=${sModelsId}&token=${token}`, {
         method: 'POST',
       },
       (t, status) => { // 上传完成
         if (status === 200) {
           // 关闭转圈等待框
           wt.close();
           if (commonUtils.isNotEmptyObject(t.responseText)) {
             try {
               const responseObj = JSON.parse(t.responseText);
               if (commonUtils.isNotEmptyObject(responseObj) && responseObj.code === 1) {
                 /* 拿到上传返回的数据库地址 */
                 const dataReturn = responseObj.dataset.rows;
                 if (commonUtils.isNotEmptyArr(dataReturn) && dataReturn.length > 0) {
                   /* 通过文件名拿到文件地址222 */
                   const fileName = dataReturn[0].fileName;
                   const filePath = dataReturn[0].filePath;
                   /* 上传到通用文件管理中 */
                   const imgObj = {};
                   imgObj.filePath = filePath;
                   imgObj.fileName = fileName;
                   files.push(imgObj);
                   this.uploadImage(imgObj);
                 }
               } else {
                 alert(responseObj.msg);
               }
             } catch (e) {
               alert(`解析地址失败:${e}`);
             }
           }
           // window.location.reload();
         } else {
           alert(`上传失败:${status}`);
           // 关闭原生的转圈等待框
           wt.close();
         }
       },
     );

     task.addData('string_key', 'string_value'); // 可以向后台传值
     task.addFile(path, { key: 'testimage' });
     task.start();
   }


  handleClick =(name) => {
    if (name === 'BtnCamera') { /* 手机调动摄像头拍照 */
      this.getImage();
    } else if (name === 'BtnPhoto') { /* 手机相册选择图片 */
      this.getPhoto();
    } else if (name === 'BtnCancel') {
      window.history.back(-1);
    }
  }

  handleGetWxCode = async (successHandler) => {
    let scanResult = '';
    const { app } = this.props;
    // eslint-disable-next-line prefer-destructuring,no-unused-vars
    const userinfo = app.userinfo;
    // const myUrl = `http://${location.host}/index.html`;
    const myUrl = location.href.split("#")[0];
    // const myUrl = 'http://sztlerp.gnway.vip:62665/index.html';
    const configUrl = `${commonConfig.server_host}wechat/getWxToken`;
    const values = {
      url: myUrl,
      sBrandsId: userinfo.sBrandsId,
      sSubsidiaryId: userinfo.sSubsidiaryId,
    };
    const configReturn = (await commonServices.postValueService(null, values, configUrl)).data;
    if (configReturn.code === 1) {
      const { rows } = configReturn.dataset;/* 获取费用分摊单据配置 */
      if (commonUtils.isNotEmptyArr(rows)) {
        const appId = rows[0].appId.toString();
        const nonceStr = rows[0].nonceStr.toString();
        const signature = rows[0].signature.toString();
        const timestamp = rows[0].timestamp.toString();
        // alert(appId);
        // Toast.fail(`1-获取TokenAppId!${appId}`);
        weixin.config({
          beta: true, // 必须这么写,否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
          appId, // 必填,公众号的唯一标识
          timestamp, // 必填,生成签名的时间戳    <%= Html.Encode(ViewData["timestamp" ]) %>
          nonceStr, // 必填,生成签名的随机串
          signature, // 必填,签名
          jsApiList: ['checkJsApi', 'scanQRCode', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData'], // 必填,需要使用的JS接口列表, 这里只需要调用扫一扫
        });
        weixin.ready(() => {
          weixin.checkJsApi({ // 判断当前客户端版本是否支持指定JS接口222
            jsApiList: ['scanQRCode', 'chooseImage'],
            success(res) { // 以键值对的形式返回,可用true,不可用false。如:{"checkResult":{"scanQRCode":true},"errMsg":"checkJsApi:ok"}
              // Toast.fail(`成功校验:${res}`);
            },
            // eslint-disable-next-line no-unused-vars
            fail(res) { // 检测getNetworkType该功能失败时处理
              Toast.fail('checkJsApi error');
            },


          }); // wx.ready结束
          weixin.chooseImage({
            count: 9, // 默认9  一共选择图片数量
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success(res) {
              const localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
              // const imgHtml = '';
              let imgUrl = localIds[0];
              // Toast.fail(`2-选定照片的本地src!${imgUrl}`);
              // eslint-disable-next-line no-plusplus
              // for (let i = 0; i < localIds.length; i++) {
                // 选择照片展示
                // imgHtml = `${imgHtml}<img src="${localIds[i]}"><br>`;
                // successHandler(localIds[i]);
              // imgUrl = localIds[i];
                // imgHtml+fnGetLocalImgData(localIds[i]);
              // }
              // imgUrl = localIds[0];
              // const base64Url = this.fnGetLocalImgData(imgUrl);
              // console.log('base1111', base64Url);
              successHandler(imgUrl);
            },
            fail(res) {
              Toast.fail(`照片上传失败!${res}`);
            },
          });
        });
      } else {
        Toast.fail(configReturn.msg);
      }
    } else {
      Toast.fail(configReturn.msg);
    }
    return scanResult;
  }

  /* 处理照片上传业务 */
  handleWxBusiness = async (localIds) => {
    const { sModelsId, token, app } = this.props;
    const { files } = this.state;
    this.fnGetLocalImgData(localIds, async (base64Url) => {
      if(commonUtils.isNotEmptyObject(base64Url)) {
        const dataUrl = `${commonConfig.file_host}file/mobileuploadwechat?sModelsId=${sModelsId}&token=${token}`;
        /*  将二进制地址存储到数据中 */
        const value ={ picUrl : [base64Url]};
        const returnData = (await commonServices.postValueService(app.token, value, dataUrl)).data;
        /* 拿到上传返回的数据库地址 */
        const dataReturn = returnData.dataset.rows;
        if (commonUtils.isNotEmptyArr(dataReturn) && dataReturn.length > 0) {
          /* 通过文件名拿到文件地址 */
          const sFileName = dataReturn[0].fileName;
          const sFilePath = dataReturn[0].filePath;
          // Toast.fail(`3-照片上传成功后!${sFileName}`);
          /* 上传到通用文件管理中 */
          if(commonUtils.isNotEmptyObject(sFileName) && commonUtils.isNotEmptyObject(sFilePath)) {
            const imgObj = {};
            imgObj.filePath = sFilePath;
            imgObj.fileName = sFileName;
            files.push(imgObj);
            this.handleUploadImage(imgObj);
          }
        }
      }
    });
  }

  fnGetLocalImgData = (localID, successHandler ) => {
    weixin.getLocalImgData({
      localId: localID, // 图片的localID
      success: (res) => {
        let baseUrL = '';
        let { localData } = res; //  localData是图片的base64数据,可以用img标签显示
        // if (localData.startsWith('data:image')) { // 判断是否有这样的头部
        //   // 没有则加上头部
        //   localData = `data:image/jpeg;base64,${localData}`;
        // }
        // 去掉所以换行符
        localData = localData.replace(/\r|\n/g, '');
        // return `<img src="${localData}"><br>`;
        baseUrL =  localData;
        successHandler(baseUrL);
      },
    });
  }

  /* 微信拍照 */
  handleWxPhoto = async () => {
    this.handleGetWxCode((code) => {
      if (!commonUtils.isEmpty(code)) {
        this.handleWxBusiness(code);
      }
    });
  }

  /* 微信二进制 */
  handleWxPhotoScream = async () => {
    this.handleGetWxCode((code) => {
      if (!commonUtils.isEmpty(code)) {
        this.handleWxBusiness(code);
      }
    });
  }

  // /* 图片上传入库 */
  handleUploadImage = (imageObj) => {
    if (commonUtils.isNotEmptyObject(imageObj) && commonUtils.isNotEmptyObject(imageObj.filePath)) {
      /* -封装slaveData */
      const name = 'slave';
      const { app } = this.props;
      let { slaveData } = this.props;
      let { imageData } = this.state;
      if (commonUtils.isEmpty(slaveData) || commonUtils.isEmpty(imageData)) {
        slaveData = [];
        imageData = [];
      }
      const { currentPane } = app;
      /* 上传图片 */
      const tableDataRow = this.props.onDataRowAdd(name, true);/* 选中行 */
      tableDataRow.iOrder = 0;
      tableDataRow.sSrcNo = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcNo : '';
      tableDataRow.sSrcFormId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcFormId : '';
      tableDataRow.sSrcId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcId : '';
      tableDataRow.sSrcSlaveId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcSlaveId : '';
      tableDataRow.sPicturePath = imageObj.filePath;
      tableDataRow.sFileName = imageObj.fileName;
      if (commonUtils.isNotEmptyObject(imageObj.filePath)) {
        imageData.push(imageObj.filePath);
      }
      slaveData.push(tableDataRow);
      this.props.onSaveState({ slaveData, imageData });
      this.props.onSubmit();/* 通用保存 */
    }
  }

  readAsDataURL = async()=> {
     const { sModelsId, token, app } = this.props;
     let { slaveData } = this.props;
     let { imageData } = this.state;
     const files = [];
    //检验是否为图像文件
    var file = document.getElementById("file").files[0];
    if (!/image\/\w+/.test(file.type)) {
      alert("看清楚,这个需要图片!");
      return false;
    }
    const onUploadImage = this.handleUploadImage;
    var reader = new FileReader();
    //将文件以Data URL形式读入页面
    reader.readAsDataURL(file);
    reader.onload = async function (e) {
      const urlArr = [reader.result];
      const dataUrl = `${commonConfig.server_host}file/mobileuploadwechat?sModelsId=${sModelsId}&token=${token}`;
      /*  将二进制地址存储到数据中 */
      const value ={ picUrl : urlArr};
      const returnData = (await commonServices.postValueService(app.token, value, dataUrl)).data;
      /* 拿到上传返回的数据库地址 */
      const dataReturn = returnData.dataset.rows;
      if (commonUtils.isNotEmptyArr(dataReturn) && dataReturn.length > 0) {
        /* 通过文件名拿到文件地址 */
        const sFileName = dataReturn[0].fileName;
        const sFilePath = dataReturn[0].filePath;
        /* 上传到通用文件管理中 */
        if(commonUtils.isNotEmptyObject(sFileName) && commonUtils.isNotEmptyObject(sFilePath)) {
          const imgObj = {};
          imgObj.filePath = sFilePath;
          imgObj.fileName = sFileName;
          files.push(imgObj);
          onUploadImage(imgObj);
        }
      }
    }
  }

  render() {
    const {
      config: btnUpdConfig, btnStyle, app,
    } = this.props;
    const { files } = this.state;
    const dWidth = document.documentElement.clientWidth || document.body.clientWidth; /* 获取手机视窗宽度 */
    const dHeight = document.documentElement.clientHeight || document.body.clientHeight; /* 获取手机视窗宽度 */
    /* 上传照片样式定位 */
    let imgDivTop = '500';
    const mobileBarStyle = document.getElementsByClassName('am-list-view-scrollview-content');
    if (commonUtils.isNotEmptyArr(mobileBarStyle) && mobileBarStyle.length > 0) {
      const obj = mobileBarStyle[0].getBoundingClientRect();
      const objHeight = mobileBarStyle[0].clientHeight;
      if (commonUtils.isEmptyObject(obj)) {
        if (obj.top < dHeight) {
          imgDivTop = Math.floor(obj.top + objHeight);
        }
      }
    }

    return (
      <div>
        {commonUtils.isEmptyObject(btnUpdConfig) ? '' :
        <div className="content">
          <div className={styles.commonImage} id="imgDiv" key="imgDivKey" style={{ top: imgDivTop }}>
            {
              commonUtils.isNotEmptyArr(files) && files.length > 0 ?
                files.map((child) => {
                if (commonUtils.isNotEmptyObject(child.filePath)) {
                  const { token } = app;
                  let imgBox = '';
                  const picAddr = commonUtils.isNotEmptyObject(child.filePath) ? child.filePath.split(',') : '';
                  const previewImageArr = [];
                  if (commonUtils.isNotEmptyArr(picAddr)) {
                    picAddr.forEach((item) => {
                      const dataPreviewUrl = `${commonConfig.server_host}file/download?savePathStr=${item}&width=${dWidth}&&height=${dHeight}&sModelsId=100&token=${token}`; /* 预览 */
                      previewImageArr.push(dataPreviewUrl);
                    });
                    const dataUrl = `${commonConfig.server_host}file/download?savePathStr=${picAddr[0]}&width=80&&height=80&sModelsId=100&token=${token}`; /* 缩略图 */
                    // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
                    imgBox = <img src={dataUrl} alt="img" onFocus={() => 0} onClick={e => preView(previewImageArr, e)} />;
                  }
                  return imgBox;
                } else {
                  return '';
                }
              }) : ''
            }
          </div>
          {/*<Button type="button" inline disabled={false} onClick={() => this.handleUploadPhoto('slave')} style={btnStyle}>*/}
          {/*  上传图片*/}
          {/*</Button>*/}
          <Button type="button" inline disabled={false} onClick={() => this.handleWxPhoto()} style={btnStyle}>
            上传图片
          </Button>
          {/*<input type="file" id="file"/>*/}
          {/*<Button type="button" onClick={() => this.readAsDataURL()} >读取图片</Button>*/}
          {/*<div id="result" ></div>*/}
          {/* <Button */}
          {/*  inline */}
          {/*  style={btnStyle} */}
          {/*  // disabled={!enabled} */}
          {/*  onClick={() => */}
          {/*    Modal.alert('', <div />, [ */}
          {/*      { text: '拍照', onPress: () => this.handleWxPhoto('BtnCamera') }, */}
          {/*    ]) */}
          {/*  } */}
          {/* >{btnUpdConfig.showName} */}
          {/* </Button> */}
        </div>
        }
      </div>

    );
  }
}

export default CommobileBase(CommobileClassifyEvent(FileManageMobile));