如果我有URI,如何将文件上传到ionic2 app中的服务器?

时间:2017-06-01 15:12:57

标签: html angular ionic-framework ionic2

我现在正在使用这个离子原生插件MSDN,它可以为我提供图像文件URI(例如,iOS上的assets-library://或Android上的content://。但我不知道如何将此文件上传到我的服务器。我应该使用带有<input type="file">的普通html表单吗?

2 个答案:

答案 0 :(得分:1)

根据您的后端类型,有各种解决方案。如果你使用NoSQL,你可以传输和存储base64格式的图像。

E.g。

import {
  BarcodeScanner,
  File,
  ImagePicker,
  ImagePickerOptions,
  ImageResizer,
  ImageResizerOptions
} from 'ionic-native';

import filenameRegex from 'filename-regex';
import dirnameRegex from 'dirname-regex';

export interface ImageBlob {
  name: string;
  blob: string;
}

export function pickImage(options: ImagePickerOptions = {}): Promise<ImageBlob> {
    interface ImagePath {
        name: string;
        dir: string;
        path: string;
    };

    const imagePickerOptions : ImagePickerOptions =
        options == null ? { maximumImagesCount: 1 } as ImagePickerOptions : options;

    function extractSingleImage(images: string | Array<string>): Promise<ImagePath> {
        return new Promise((resolve, reject) => {
            let imagePath: string = images instanceof Array ? images[0] : images;

            let filename: string = imagePath.match(filenameRegex())[0];
            let dirname: string = imagePath.match(dirnameRegex())[1];

            if (filename == null || dirname == null) {
                reject(new ReferenceError('Invalid image\'s path'));
            } else {
                resolve({
                    name: filename,
                    dir: dirname,
                    path: imagePath
                });
            }
        });
    }

    function resizePicture(
        image: ImagePath,
        resizerOptions?: ImageResizerOptions
    ): Promise<any> {
        const options: ImageResizerOptions = resizerOptions || {
            uri: image.path,
            folderName: 'pictures',
            width: 1024,
            height: 1024,
            quality: 90
        };

        return ImageResizer
            .resize(options)
            .catch(err => console.error("Cannot resize", err));
    }

    function readAsDataUrl(image: ImagePath): Promise<ImageBlob> {
        return File
            .readAsDataURL(image.dir, image.name)
            .then(blob => ({ blob, name: image.name }))
            .catch(err => console.error("Cannot read file as data-url", err));
    }

    return ImagePicker
        .getPictures(imagePickerOptions)
        .then(extractSingleImage)
        .then(resizePicture)
        .then(extractSingleImage)
        .then(readAsDataUrl);
}

请注意,上面的代码适用于ionic-angular@2.2.0ionic-native@2.4.1。所以最新的离子改变了API。

答案 1 :(得分:1)

请安装FilePath插件以获取本机路径。然后使用以下代码。比如说你正在选择一个图像文件。

nativepath: any;
uploadfn(){
   this.fileChooser.open().then((url) => {
  (<any>window).FilePath.resolveNativePath(url, (result) => {
    this.nativepath = result;
    this.readimage();
  }
  )
})
}  

readimage() {
    (<any>window).resolveLocalFileSystemURL(this.nativepath, (res) => {
      res.file((resFile) => {
        var reader = new FileReader();
        reader.readAsArrayBuffer(resFile);
        reader.onloadend = (evt: any) => {
          var imgBlob = new Blob([evt.target.result], { type: 'image/jpeg'});
          //do what you want to do with the file
        }
      })
    })
  }

请看这里 - http://tphangout.com/ionic-2-serving-images-with-firebase-storage/

(讨论如何从手机的文件系统中选择图像并将其上传到firebase存储中)

希望这对你有所帮助。感谢。