如何使用 Ionic 2 上传图片

How to upload a picture with Ionic 2

我正在使用 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) => {
}); 

但是我不知道它把图片保存在哪里,也不知道怎么发到服务器。我在 Internet 上找不到任何内容。

谢谢

注意/编辑:此代码适用于 AngularJS,以前称为 Angular。我将把展示留给那些 google 并偶然发现这个搜索 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'})
        }

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

options = {
saveToPhotoAlbum: true
}

(您也可以修改 destinationType)。

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

希望对您有所帮助。谢谢

在 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])

希望对您有所帮助!

这就是您捕获和保存/缓存图像的方式。

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

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

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

然后从Transfer中调用上传函数class。

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

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