ionic4 圖片上傳

寫(xiě)了這么多的圖片上傳,今天想著要好好總結(jié)下了
上傳圖片要安裝一些插件是必不可少的

1.插件安裝如下:
(1) 文件傳輸插件

ionic cordova plugin add cordova-plugin-file-transfer
npm install @ionic-native/file-transfer

(2) 文件插件

ionic cordova plugin add cordova-plugin-file
npm install @ionic-native/file

(3) 拍照插件

ionic cordova plugin add cordova-plugin-camera
npm install @ionic-native/camera

2.代碼流程如下
(1)拍照獲取照片,使用base64格式的照片編碼

const options: CameraOptions = {
    quality: 100,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.PNG,
    mediaType: this.camera.MediaType.ALLMEDIA,
    sourceType: this.camera.PictureSourceType.CAMERA,
    targetWidth: 400,
    targetHeight: 400,
    cameraDirection: 1
}

this.camera.getPicture(options).then((imageData) => {
  let base64Image = 'data:image/png;base64,' + imageData;
  console.log(base64Image, 'base64Image');
  this.doUpload(base64Image);
}, (err) => {
  // Handle error
});

(2)將獲取的圖片上傳到服務(wù)器

doUpload(fileSrc){
let that = this;
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
  fileKey: 'file',
  fileName: fileSrc.substr(fileSrc.lastIndexOf('/') + 1),  //名稱
  mimeType: 'image/png',
  httpMethod: "POST",
}
var api =""; //后臺(tái)給的上傳接口
fileTransfer.upload(fileSrc, api, options)
  .then(async (res: any) => {
    console.log(res)
  }, (err) => {
    console.log(err);
  })
}

插件下載鏈接地址:
(1)https://ionicframework.com/docs/native/camera
(2)https://ionicframework.com/docs/native/file-transfer
(3)https://ionicframework.com/docs/native/file

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容