从NativeScript将图像上传到Firebase

时间:2017-01-31 14:53:10

标签: firebase nativescript firebase-storage

我正在尝试使用NativeScript的相机模块拍摄照片,然后将其上传到Firebase,但它似乎无法正常工作。 imageTakenfileLocation显示为falseundefined。我的代码有问题吗? (用TypeScript编写)

import fs = require('file-system')
import frame = require('ui/frame')
import utils = require('utils/utils')
import observableModule = require('data/observable')
import imageSource = require("image-source")
import camera = require('camera')
import image = require('ui/image')
import {
  ImageFormat
} from 'ui/enums'
import view = require("ui/core/view")
import firebase = require('nativescript-plugin-firebase')
var dialog = require('nativescript-dialog')
var pd = new observableModule.Observable()

var imageContainer
var imageTaken = false
var fileLocation

exports.loaded = args => {
  var page = args.object
  imageContainer = view.getViewById(page, "img")

  pd.set('imageTaken', imageTaken)
  page.bindingContext = pd
}

exports.takePhoto = args => {
  const options = {
    width: 300,
    height: 300,
    keepAspectRatio: true
  }
  camera.takePicture().then((picture) => {
    console.log('Take Picture')
    var image = new image.Image()
    image.imageSource = picture
    imageContainer.imageSource = picture
    let savePath = fs.knownFolders.documents().path;
    let fileName = 'img_' + new Date().getTime() + '_' + this.currentUserId.getValue() + '.' + ImageFormat.jpeg
    let filePath = fs.path.join(savePath, fileName)
    console.log(filePath)
    picture.saveToFile(filePath, ImageFormat.jpeg)
    fileLocation = filePath
    imageTaken = true

  })
}

exports.sendPhoto = args => {
  console.log(imageTaken)
  console.log(fileLocation)
  imageTaken ? upload(Math.random() + '-' + Date.now()) : dialog.show({
    title: "Error",
    message: "Please take a photo first.",
    okButtonText: "OK"
  })
}

const upload = (remoteFileName) => {
  firebase.uploadFile({
    remoteFullPath: 'uploads/images/' + remoteFileName,
    localFile: fs.File.fromPath(fileLocation),
    localFullPath: fileLocation,
    onProgress: function (status) {
      console.log("Uploaded fraction: " + status.fractionCompleted)
      console.log("Percentage complete: " + status.percentageCompleted)
    }
  }).then(
    uploadedFile => {
      console.log("File uploaded: " + JSON.stringify(uploadedFile))
    },
    error => {
      console.log("File upload error: " + error)
    }
  )
}

1 个答案:

答案 0 :(得分:1)

旧相机模块已过时。请改用nativescript-camera。请注意,对于Android API23 +,您需要显式请求权限运行时。使用nativescript-camera完成

import * as camera from "nativescript-camera";
camera.requestPermissions();

有关nativescript-camera插件的更多信息here