如何使用Ionic 2上传图片

Mar*_*ayo 4 django django-rest-framework ionic-framework ionic2

我正在使用Ionic 2和Django Rest Framework构建应用程序.我需要从画廊或相机拍摄照片并将此照片上传到我的服务器.

我有这个代码打开相机并拍照.

options = {}
Camera.getPicture(options).then((imageData) => {
    // imageData is either a base64 encoded string or a file URI
    // If it's base64:
    let base64Image = "data:image/jpeg;base64," + imageData;
}, (err) => {
}); 
Run Code Online (Sandbox Code Playgroud)

但我不知道它在哪里保存图片或如何将其发送到服务器.我在互联网上找不到任何东西.

谢谢

M. *_*bib 6

在IONIC 2中,您将执行类似这样的操作,以便从图库或相机中获取图片(通过更改源类型).它会以base64字符串格式为您提供该图像.

pickPicture(){

  Camera.getPicture({
      destinationType: Camera.DestinationType.DATA_URL,
      sourceType     : Camera.PictureSourceType.PHOTOLIBRARY,
      mediaType: Camera.MediaType.PICTURE
  }).then((imageData) => {
    // imageData is a base64 encoded string
      this.base64Image = "data:image/jpeg;base64," + imageData;
  }, (err) => {
      console.log(err);
  });
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用HTTP请求将此base64字符串发送到服务器.

private http: Http
this.http.post("http://localhost:3000", this.base64Image)
                           .map((res:Response) => res.json())
                           .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
Run Code Online (Sandbox Code Playgroud)

在服务器端接收后,你可以解码它并做任何你想做的事情,就像这样.

 Base64.decode64(image_data[:content])
Run Code Online (Sandbox Code Playgroud)

我希望它会有所帮助!