关于ionic3:Ionic 3使用cordova-plugin-file将相机图像发布到API

Ionic 3 Post Camera Image to API With cordova-plugin-file

我已经成功地使用cordova-plugin-file-transfer将图像文件从设备相机发布到API,例如fileTransfer.upload(fileUrl,url,options)。

但是,不建议使用cordova-plugin-file-transfer:
"通过XMLHttpRequest中引入的新功能,该插件不再需要。从此插件迁移到使用XMLHttpRequest的新功能,将在此Cordova博客文章中进行解释。"
https://github.com/apache/cordova-plugin-file-transfer

建议的新方法是使用cordova-plugin-file和XMLHttpRequest。
https://cordova.apache.org/blog/2017/10/18/from-filetransfer-to-xhr2.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
    console.log('file system open: ' + fs.name);
    fs.root.getFile('bot.png', { create: true, exclusive: false }, function (fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();
            reader.onloadend = function() {
                // Create a blob based on the FileReader"result", which we asked to be retrieved as an ArrayBuffer
                var blob = new Blob([new Uint8Array(this.result)], { type:"image/png" });
                var oReq = new XMLHttpRequest();
                oReq.open("POST","http://mysweeturl.com/upload_handler", true);
                oReq.onload = function (oEvent) {
                    // all done!
                };
                // Pass the blob in to XHR's send method
                oReq.send(blob);
            };
            // Read the file as an ArrayBuffer
            reader.readAsArrayBuffer(file);
        }, function (err) { console.error('error getting fileentry file!' + err); });
    }, function (err) { console.error('error getting file! ' + err); });
}, function (err) { console.error('error getting persistent fs! ' + err); });

在上面的示例中,我们可以将XMLHttpRequest替换为Angular 5 HttpClient,例如

1
this.http.post(path, body, options);

cordova-plugin-camera文档建议使用DestinationType = FILE_URI或NATIVE_URI,它们均返回类似于以下内容的路径/文件:content:// media / external / images / media / 1249。他们特别警告不要返回base64编码的字符串。

"返回base64编码的字符串。DATA_URL可能占用大量内存,并导致应用程序崩溃或内存不足错误。如果可能,请使用FILE_URI或NATIVE_URI。"
https://github.com/apache/cordova-plugin-camera#module_Camera.DestinationType

似乎这里的新方法/正确方法是使用cordova-plugin-file获取文件,将此文件转换为blob,然后将其发布到API。

首先,我认为我需要使用cordova-plugin-file中的resolveLocalFilesystemUrl转换照相机localFile:https://ionicframework.com/docs/native/file/。

1
2
3
this.file.resolveLocalFilesystemUrl(localFile).then((entry) => {
    console.log(entry.fullPath);
});

Android示例:

1
2
localFile: content://media/external/images/media/1249
resolvedLocalFile: content://media/external/images/media/1827

但是,我一直无法使用带有cordova-plugin-file的resolveLocalFile来获取文件并转换为blob(然后最终发布到API)。

这是正确的方法吗?如果是这样,那么这是一个有效的代码示例。如果没有,正确的方法是什么?请注意,我已经看到了一些示例,这些示例发布了base64编码的字符串,但是cordova-plugin-camera明确警告了这一点。


以下是基于此方法的有效Stubbing:使用cordova-plugin-file获取文件,将文件转换为blob,将blob发布到API。这篇文章对创建此Stubbing也非常有帮助:https://golb.hplar.ch/2017/02/Uploading-pictures-from-Ionic-2-to-Spring-Boot.html

主例程:

1
2
3
4
5
6
7
this.cameraProvider.getPicture()
    .flatMap(imageData => {
        return this.cameraProvider.imageDataToBlob(imageData);
    })
    .flatMap(blob => {
        return this.workerProvider.updateImage(blob);
    }).subscribe();

使用cordova-plugin-camera获取文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public getPicture(): Observable {

    const options: CameraOptions = {
        destinationType: this.camera.DestinationType.FILE_URI,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE,
        sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
    }

    return Observable.fromPromise(
        this.platform.ready().then(() => {
            if (this.platform.is('cordova')) {
                return this.camera.getPicture(options).then((imageData: any) => {

                    // Android DestinationType.FILE_URI returns a local image url in this form: content://media/external/images/media/1249
                    // iOS DestinationType.FILE_URI returns a local image url in this form: file:///var/mobile/Containers/Data/Application/25A3F622-38DB-4701-AB20-90AAE9AC02C8/tmp/cdv_photo_002.jpg
                    return imageData;

                }).catch((error) => {
                    // Handle error.
                })
            }
            else {
                return Observable.of(null);
            }
        })
    )
}

将文件转换为blob:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public imageDataToBlob(imageData): Observable {

    return Observable.fromPromise(this.file.resolveLocalFilesystemUrl(imageData))
        .flatMap((fileEntry: FileEntry) => { // Cast entry to fileEntry.
            return this.fileEntryToObservable(fileEntry)
        })
        .flatMap((file) => {
            return this.fileReaderToObservable(file)
        });
}

public fileEntryToObservable(fileEntry: any): Observable {

    return Observable.create(observer => {
        // Success.
        fileEntry.file(function(file) {
            observer.next(file);
        },
        // Error.
        function (error) {
            observer.error(error)
        })
    });
}

public fileReaderToObservable(file: any): Observable {

    const fileReader = new FileReader();
    fileReader.readAsArrayBuffer(file);

    return Observable.create(observer => {
        // Success.
        fileReader.onload = ev => {
            let formData = new FormData();
            let imgBlob = new Blob([fileReader.result], { type: file.type });
            observer.next(imgBlob);
        }
        // Error.
        fileReader.onerror = error => observer.error(error);
    });
}

将Blob发布到API:

1
2
3
4
5
6
7
8
// Do NOT add Content-Type multipart/form-data to header.
let headers = new HttpHeaders()

const formData = new FormData();
formData.append('file', blob, 'image');

let options = { headers: headers };
return this.http.post(url, formData, options);