首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

ionic3不用插件用(html5)做的上传

2024-12-20 来源:化拓教育网

page页面:

这个是看到的要上传的图片
  <img src="../../asset/upload.png"   class="blueButton"/>
  <input accept="image/*" type="file" class="myFileUpload" (change)="fileupload($event,1)" />

page css:

  /*蓝色按钮,绝对定位*/
  .blueButton {
    position: absolute;
    display: block;
    width: 100px;
    height: 40px;
    text-decoration: none;
    text-align: center;
    font: normal normal normal 16px/40px 'Microsoft YaHei';
    cursor: pointer;
    border-radius: 4px;
  }
  /*自定义上传,位置大小都和a完全一样,而且完全透明*/
  .myFileUpload {
    position: absolute;
    display: block;
    width: 100px;
    height: 40px;
    opacity: 0;
  }

page ts:

//选择图片
  fileupload(event, type) {
    let that = this;
    let files = event.target.files;
    if (files && files.length > 0) {
      let file = files[0];
      that.uploadFileWithServe(file, type);
    }
  }

  async uploadFileWithServe(image, type) {
    let loader = this.loadingCtrl.create({
      content: "上传中..."
    });
    loader.present();
    try {
      let Imgresult: any;
      Imgresult = await this.http.uploadFile("headimage", image, null);
    
      loader.dismiss();
    } catch (error) {
      this.util.showToast(error.msg);
      loader.dismiss();
    }
  }
/** 
   * 上传文件
   * @param path 传到那个目录下
   * @param file  文件
   * @param type 类型   视频传到video ,图片传到files
   */
  uploadFile(path, file, type): Promise<any> {
    return new Promise<any>(async (resolve, reject) => {
      try {
        let userInfo = this.storage.get('user');
        let form = new FormData();
        let url: any;
        if (Boolean(type)) {
          url = APP_SERVE_URL + "files/" + type; //服务器上传地址
        } else {
          url = APP_SERVE_URL + "files"; //服务器上传地址
        }

        form.append('file', file);
        let xhr = new XMLHttpRequest();
        xhr.open("post", url, true);
        xhr.setRequestHeader('path', path);
        xhr.setRequestHeader('email', userInfo.email);
        xhr.setRequestHeader('token', userInfo.token);
        //上传进度事件
        // xhr.upload.addEventListener("progress", function (result) {
        //   if (result.lengthComputable) {
        //     //上传进度
        //     var percent = (result.loaded / result.total * 100).toFixed(2);
        //     console.log(percent);
        //   }
        // }, false);
        xhr.addEventListener("readystatechange", function () {
          var result = xhr;
          if (result.status != 200) { //error
            reject(result);
          }
          else if (result.readyState == 4) { //finished
            resolve(JSON.parse(result.response));
          }
        });
        xhr.send(form); //开始上传
      } catch (error) {
        reject(error);
      }
    });
  }
显示全文