NativeScript 如何保存图像选择器选择的文件

NativeScript how to save imagepicker selected file

我正在尝试 select 用户图库中的图片,在 ImageView 中查看,然后保存以供上传。

我正在使用 nativescript-imagepicker 插件。

以下是我如何 select 来自画廊的图像并将其设置在 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

我做错了什么?

当您从图库中获取所选项目时,您可以使用 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