ionic4 图片上传

写了这么多的图片上传,今天想着要好好总结下了
上传图片要安装一些插件是必不可少的

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)将获取的图片上传到服务器

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 =""; //后台给的上传接口
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

你可能感兴趣的:(ionic4 图片上传)