django - 如何使用 Ionic 2 上传图片

标签 django ionic-framework django-rest-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) => {
}); 

但我不知道它把图片保存在哪里,也不知道如何将它发送到服务器。我在互联网上没有找到任何东西。

谢谢

最佳答案

在 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);
  });
}

现在您可以像这样使用 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'));

在服务器端收到它后,您可以对其进行解码并做任何您想做的事情,就像这样。

 Base64.decode64(image_data[:content])

我希望它会有所帮助!

关于django - 如何使用 Ionic 2 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36329819/

相关文章:

django 网络应用程序测试

ios - UIWebView 向 Apple 提交 ionic 应用程序时出错

ios - 如何将音频从设备扬声器路由到蓝牙扬声器?

python - 在Django中对要请求的图片进行排队

django - 我可以在 Django 中使用数据库 View 作为模型吗?

python - 使用具有多对多关系的 Post 方法的 Django Rest-Framework 错误

python - 自定义过滤器字段测试不起作用

javascript - Ionic(Angular)从数组中获取正确的数据

python - GenericRelatedObjectManager 不是 JSON 可序列化的

python - DRF - 具有非模型 write_only 字段的 ModelSerializer