我正在使用 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/