NativeScript如何保存imagepicker所选文件

时间:2016-12-19 12:13:32

标签: nativescript

我正在尝试从用户的图库中选择一张图片,在ImageView中查看该图片,然后保存以供上传。

我正在使用nativescript-imagepicker插件。

以下是我如何从图库中选择图片并将其设置在ImageView

export function selectPicture() :void{
    let context = imagePicker.create({
        mode : "single"
    });
    context.authorize()
        .then(()=>{ return context.present();})
        .then((selection)=>{
            selection.forEach((selected)=>{
                selected.getImage().then((value :ImageSource)=>{
                    imageView.imageSource = value;
                })
            })
        });
}

这就是我保存并上传它的方式:

export function upload():void{

    try {
        let photoPath = FileNameService.generatePictureFilePath();
        let fileName = FileNameService.getFilenameFromPath(photoPath);
        //this is where I get the error
        **fromAsset(imageView.src)**.then(
            (res) => {
            imageSource = res;        
            let saved  = imageSource.saveToFile(...);
            if(saved){//doStuff },
        (error)=>{
            alert("Error " + error);
        })
    }catch (e){
        alert(e);
    }
}

fromAsset函数抛出以下错误:

asset.getImageAsync is not a function

我做错了什么?

1 个答案:

答案 0 :(得分:1)

当您从图库中获取所选项目时,您可以使用ImageSource saveToFile(<path>, <file_format>);方法来保存图像。然后,您将能够使用文件路径将图像上载到所需的后端服务。您可以查看下面附带的示例。

function startSelection(context) {
    context
        .authorize()
        .then(function() {
            imageItems.length = 0;
            return context.present();
        })
        .then(function(selection) {
            selection.forEach(function(selected_item) {
                selected_item.getImage().then(function(imagesource){
                    let folder = fs.knownFolders.documents();
                    let path = fs.path.join(folder.path, "Test"+counter+".png");
                    let saved = imagesource.saveToFile(path, "png");

                    if(saved){
                        var task = sendImages("Image"+counter+".png", path);
                        var item = new observable.Observable();
                        item.set("thumb", imagesource);
                        item.set("uri", "Test"+counter+".png");
                        item.set("uploadTask", task);

                        imageItems.push(item);
                    }
                    counter++;
                })

            });
        }).catch(function (e) {
            console.log(e);
        });
}

要获得进一步的帮助,您还可以查看示例项目here

相关问题