2017-01-31 115 views
0

我試圖用NativeScript的相機模塊拍攝照片,然後將其上傳到Firebase,但似乎不起作用。 imageTakenfileLocationfalseundefined。我的代碼有問題嗎? (用TypeScript寫)從NativeScript將圖片上傳到Firebase

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

舊相機模塊已過時。改爲使用nativescript-camera。請注意,對於Android API23 +,您需要明確請求權限運行時。隨着nativescript相機是大約nativescript相機插件here

+0

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

完成更多的工作,最後,這是什麼解決它。謝謝!只是問,你知道爲什麼他們仍然有相機在文檔中,如果它的過時? – hashtagmemes

+0

從昨天開始,相機文章更新了這一個https://docs.nativescript.org/hardware/camera .. NativeScript文檔每次發佈都會更新,這可能是爲什麼舊文章處於活動狀態的原因昨天(當新版本被宣佈) –