In Ionic3 / 4 how to upload images (photographs / picture selection)

[Talk is cheap. Show me the code]

I do not want to see the theoretical knowledge directly venue last code sample.

(This article is recommended to look at the whole idea)

Initially I used the time to write APP Ionic3, today to see the next document, Ionic4 3 relative to the document description clearer, the code more streamlined, the community is really getting better a little happy about. But some critics say Ionic4 3 relative to more complex, more pit.

End mobile phones to upload pictures, there are two ways one is upload pictures other is the picture choice (Please note the difference between the selected file here) Once uploaded, ado into the topic.

Upload pictures:

One, the pre-conditions

1.1, introduced js and local dependence, so that we can use the camera to some api

npm install --save @ionic-native/cameranpm install --save @ionic-native/camera

1.2 plug-ins add cordova

ionic cordova plugin add cordova-plugin-camera

Then generates in config.xml, sometimes you need to add yourself to go

<plugin name="cordova-plugin-camera" spec="^4.0.3" />

Relative android, ios for control authority to be more stringent, ios10 less you need to add the following code at the bottom config.xml:

<!-- Required for iOS 10: Camera permission prompt -->
<edit-config file="*-Info.plist" mode="merge" target="NSCameraUsageDescription">
    <string>Used to take pictures</string>
</edit-config>

Second, the realization of ideas and logic

1. Call the camera, take pictures

2. Place

this.camera.getPicture(options).then(()=>{})

Pictures of base64 returned backstage pass, after the request is successful, there needs to back with our return of a picture thumbnail URL, to help us to echo the page. Of course Ionic4 itself also provides a picture compression functions. Use images returned by the backend significant back and forth to the page just to make sure pictures uploaded successfully. We must take into account a variety of network problems in production environments.

3. In the image upload process, we need to monitor the camera plug itself and then catch status, and timely feedback to the user information, call this.toast ( 'image upload failed') after the failure.

Third, the sample code

3.1, root module (app / src / app.module.ts) injecting Camera.

Import camera module

import { Camera } from '@ionic-native/camera';

providers injected, of course, you can also see other needed services as well as configure my injection for the project.

  providers: [
    Camera,     //相机拍照
    imagePicker,//图片选择
    {provide: ErrorHandler, useClass: IonicErrorHandler},
  ]

HTML page

   <div id="license" (click)="takePicture()">
      <div class="error-loading" *ngIf="uploadLinFail" >
    	 <img src="assets/img/login/loading.gif" alt="" class="camera">
    	 图片上传中..
      </div>
      <img class="img-scale"  [src]="ImageScale" *ngIf="ImageScale"/>
      <div *ngIf="currentImage">
    	  <img src="assets/img/login/camera.png" alt="" class="camera">
    	  营业执照
      </div>
  </div> 

.ts page

01. Import

import { Camera, CameraOptions } from '@ionic-native/camera';

02.constructor injected

private camera: Camera

03. declare variables

currentImage:any = true;//点击之后影藏当前的图片,显示loading
ImageScale:any;//后台返回的缩略图
uploadLinFail:false;//loading默认false,执行上传过程中的加载动画


04. Methods

takePicture() {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    }

    this.camera.getPicture(options).then((imageData) => {
      let ImageBase = 'data:image/jpeg;base64,' + imageData;
      this.currentImage = false;
      this.uploadLinFail = true;
      this.httpPost(ImageBase)	//httpPost上传图片的方法将图片传参到http请求方法中即可
      
    }, (err) => {
     // Handle error
     console.log("Camera issue:" + err);
     this.toast("图片上传失败")
    });
}

httpPost here () is a normal http request, write according to their own business.

File Upload:

First, we need to pay attention

File upload There is a very serious misunderstanding, image upload is not equal to part of the file upload file upload, namely: file upload can upload video, image, apk and so on. But the picture upload can upload pictures, so when choosing API time to pay attention:

1、fileTransfer.upload
2、imagePicker.getPictures

The difference between these two API is great, we must pay attention to the choice, including the choice of fileTransfer are many blog.

Second, the sample code

Similarly, we need to install the Ionic module so that we can find the appropriate API, so that you can install plug-Cordova run it on a physical device to us.

ionic cordova plugin add cordova-plugin-telerik-imagepicker
npm install @ionic-native/image-picker

.ts file

constructor(private imagePicker: ImagePicker) { }

use:

option的参数所有都为 number 类型

const option:imagePickerOption = {
maximumImagesCount : 1,	// 可选择的图片数量默认 15,1为单选
width : 400  ,		// 图片宽
height : 500 ,		//图片高
quality :  80 ,		//图片质量,质量越高图片越大,请根据实际情况选择
outputType : 0		
/** 文件输出类型,你可以选择图片URL,或者base64的文件编码
这里建议选择文件编码  0  :文件地址  1:图片base64编码*/
}

this.imagePicker.getPictures(options).then((results) => {
/**这里results返回的是一个数组,可以通过  results.pop()返回最后一个值,shift()返回第一个值,如果你只允许选择一个图片的话
,两者都是可以的,为了程序健壮性,这里建议你对results的长度进行判断处理。*/

  for (var i = 0; i < results.length; i++) {
      console.log('Image URI: ' + results[i]);
  }
}, (err) => { });

If you have any comments on this article are welcome to leave a comment below the article, I will reply in the first time to see.

Guess you like

Origin blog.csdn.net/ForgivenCheney/article/details/95631152