如何使用Ionic 2上传图片

时间:2016-03-31 09:47:11

标签: 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) => {
}); 

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

由于

5 个答案:

答案 0 :(得分: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);
  });
}

现在您可以使用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])

我希望它会有所帮助!

答案 1 :(得分:2)

注意/编辑:此代码适用于AngularJS,以前称为Angular。我将为那些谷歌的人留下展示并偶然发现这个搜索Angular 1.x.解决方案

RANT :(将Angular 1.x重命名为AngularJS以及之后,将Angular2命名为Angular的整个想法是我最近看到的最愚蠢的事情之一.Angular 2和4应该命名为Angular2和Angular4,Angular 1.x应该仍然是Angular)/咆哮结束

示例是我们其中一个应用中的工作代码,应说明我的意思

$scope.takePicture = function(type) {
            if (typeof(Camera) != 'undefined') {
                var photoType = Camera.PictureSourceType.CAMERA;
                if (type == 'gallery') {
                    photoType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
                }
                var options = {
                    quality : 80, // Damir sa 75
                    destinationType : Camera.DestinationType.DATA_URL,
                    sourceType : photoType,
                    allowEdit : false, // Damir (true -> false)
                    encodingType: Camera.EncodingType.JPEG,
                    targetWidth: 625, //Damir sa 600
                    targetHeight: 800, //Damir sa 600
                    // popoverOptions: CameraPopoverOptions - Damir
                    saveToPhotoAlbum: false,
                    correctOrientation: true
                };



                $cordovaCamera.getPicture(options).then(function(imageData) {
                      $scope.images.push({slikaB64:imageData,opis:null});              
                    }, function(err) {              
                      //alert(JSON.stringify(err));
                    });
            }
            else
                $scope.images.push({slikaB64:"R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==",opis:'123'})
        }

答案 2 :(得分:2)

这是捕获和保存/缓存图像的方法。

Camera.getPicture({
  destinationType: Camera.DestinationType.FILE_URI,
  targetWidth: 1000,
  targetHeight: 1000
}).then((imageData) => {
    this.image = imageData;
}, (err) => {
  console.log(err);
});

拍完照片后,您需要上传图片。

var url = "http://your_post_url/";
var targetPath = this.image;
var filename = this.createUniqueFileName();
var options = {
  fileKey: "file",
  fileName: filename,
  chunkedMode: false,
  mimeType: "multipart/form-data",
  params : {
    "image": targetPath
  }
};
const fileTransfer = new Transfer();
fileTransfer.upload(targetPath, url, options).then(data => {
  console.log(data);
}, err => {
  console.log(err);
});

答案 3 :(得分:1)

要使用Ionic 2 Framework将图像上传到服务器,您必须使用Transfer插件。使用

安装传输插件
ionic plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/transfer

然后从Transfer类调用上传函数。

const fileTransfer: TransferObject = this.transfer.create();

  let options1: FileUploadOptions = {
     fileKey: 'file',
     fileName: 'name.jpg',
     headers: {}

  }

 fileTransfer.upload(imageDataLocalURL, 'http://localhost/ionic/upload',  options1)
.then((data) => {
 // success
 alert("success");
}, (err) => {
 // error
 alert("error"+JSON.stringify(err));
});

使用该链接了解更多https://ampersandacademy.com/tutorials/ionic-framework-version-2/upload-an-image-to-the-php-server-using-ionic-2-transfer-and-camera-plugin

答案 4 :(得分:0)

在选项中,请将saveToPhotoAlbum选项设置为true,如下所示。

options = {
saveToPhotoAlbum: true
}

(你也可以修改destinationType)。

请查看here以查看可用选项。

希望这会对你有所帮助。感谢。

相关问题