寫了這么多的圖片上傳斗遏,今天想著要好好總結(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