使用ionic 3在本地pc上传图像文件

时间:2018-05-15 12:41:10

标签: angular ionic3

如何在本地计算机上将图像文件作为json文件

上传

我想在json文件中上传图片,是否可以在json文件中上传图片文件。如果不可能,请指导我如何在资产文件夹中添加该图像文件。任何人都可以帮我解决这个问题吗?我无法弄清楚如何解决这个问题。



 import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    import { Camera, CameraOptions } from '@ionic-native/camera';
    import { HttpClient } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';

    @Component({
    selector: 'page-home',
    templateUrl: 'home.html'
    })
    export class HomePage {

    base64Image: string;

    constructor(public navCtrl: NavController,private camera: Camera,public 
    http:HttpClient) {

    }

    openCamera(){
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum : true
    }
    
    this.camera.getPicture(options).then((imageData) => {
     // imageData is either a base64 encoded string or a file URI
     // If it's base64:
     this.base64Image = 'data:image/jpeg;base64,' + imageData;
    }, (err) => {
     // Handle error
    }); 
    }

    openGallery(){
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum : true,
      sourceType : this.camera.PictureSourceType.PHOTOLIBRARY
    }
    console.log("gallery called....");
    this.camera.getPicture(options).then((imageData) => {
     // imageData is either a base64 encoded string or a file URI
     // If it's base64:
     this.base64Image = 'data:image/jpeg;base64,' + imageData;
    }, (err) => {
     // Handle error
    }); 
    }

    uploadImage(){
    console.log("upload called....");
    let url = "assets/imgs/data/file.json";
    let postData = new FormData();
    postData.append('file',this.base64Image);
    let data:Observable<any> = this.http.post(url,postData);
    data.subscribe((result) => {
    console.log(result);
    });
    }

    }
&#13;
<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
 <button ion-button full (click) = "openCamera()">Take Photo</button>
 <button ion-button full (click) = "openGallery()">Open Gallery</button>
 <img [src] = "base64Image"/>
 <button ion-button full (click) = "uploadImage()">Upload Image</button>

</ion-content>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

是的。可以的您正在将图像另存为字符串(base64)。

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

使用

之类的方法
  

writeFile(路径,文件名,文本,选项)

在您的文件上。

  

assets / imgs / data / file.json