Ionic+Capacitor中实现拍照上传服务器功能

发布于 3 年前 作者 phonegap100 1628 次浏览 来自 分享

以前我们给大家讲解过如何在Ionic中实现拍照上传服务器功能,下面我们给大家看看Ionic+Capacitor中如何实现拍照上传服务器功能。

一、拍照插件

https://capacitorjs.com/docs/apis/camera 或者 https://ionicframework.com/docs/native/camera

二、文件传输插件

https://ionicframework.com/docs/native/file-transfer

三、Ionic+Capacitor中实现拍照上传服务器

async takePicture() {
      const image = await Camera.getPhoto({
        quality: 90,
        allowEditing: false, 
        width:400,
        height:400,
        resultType:CameraResultType.Base64,    //返回base64      
        // resultType: CameraResultType.Uri,   //返回文件路径
        source: CameraSource.Camera, //配置相机拍照还是相册选择
      });     
      const imageUrl = image.base64String;     
      if (imageUrl) {       
        const base64Image = 'data:image/jpeg;base64,' + imageUrl;
        this.imgSrc = base64Image;        
        this.doUpload(base64Image);
      }
},
async doUpload(fileSrc: any) {
      const fileTransfer: FileTransferObject = await FileTransfer.create();
      const options: FileUploadOptions = {
        fileKey: "file",
        fileName: "name.jpg", //名称
        mimeType: "image/jpeg",
        httpMethod: "POST",
        params: {
          username: "我是一个测试的名称",
          age: "21",
          height: "180",
        } /*附带的一些信息*/,
        // headers: {}
      };
      const api = "https://jd.itying.com/imgupload";
      fileTransfer.upload(fileSrc, api, options).then(
        (data) => {          
          console.log("success",JSON.stringify(data));             
        },
        (err) => {          
          console.log("error",JSON.stringify(err));  
        }
      );
}

四、部分ionic 或者 cordova插件无法使用解决方法

https://capacitorjs.com/docs/android/troubleshooting#error-package-android-support-does-not-exist

npm install jetifier --save npx jetify npx cap sync android

回到顶部