Cordova从input type =" file"将文件保存到文件系统 [英] Cordova save file to filesystem from input type="file"

查看:447
本文介绍了Cordova从input type =" file"将文件保存到文件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Cordova WebView 中文件输入的文件保存到设备文件系统?

How can I save files from file input in Cordova WebView to device filesystem?

谢谢!

推荐答案

希望,你仍在寻找答案。

Hope, you are still looking for an answer.

在我的一个应用程序中,我使用了两个函数将输入#文件保存为pdf,但您也可以为其他mime类型重写这些函数。直到今天,这些功能同时适用于平台Android和iOS。

In one of my apps I use two functions to save a input#file as pdf, but you can rewrite these functions for other mime-types as well. These functions work on both plattforms Androidand iOS until today.

函数 getAppURI 用于获取可以将文件复制到的实际app-folder-name,它请求应用程序的Cache-Folder并替换最后一个子文件夹名称以获取应用程序的base-uri,非常简单。

The function getAppURI is used to get the actual app-folder-name where you can copy your file into, it requests the Cache-Folder of the App and replaces the last subfolder-name to get the base-uri of your app, its very simple.

// get your app-root-folder-name, for instance Android: file:///storage/emulated/0/Android/data/YOUR_APP_NAMESPACE/
function getAppURI(isAndroid,callback) {
    if(isAndroid) {
        window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (filesystem) {
                var cacheDir = filesystem.root.toURL();
                var startPointCacheFolderName = cacheDir.match(/\/\w+\/$/) [0];
                callback(cacheDir.replace(startPointCacheFolderName, '') + '/');
            }, function (error) {
                console.log('no access to app-filesystem', error);
            }
        );
    }
    else{
        // iOS
        // just request the filesystem so that you really have access to it
        window.resolveLocalFileSystemURL(cordova.file.documentsDirectory,
            function(entry){
                callback(entry.nativeURL);
            },
            function(error){
            console.log("no access to filesystem",error);
        });
    }
}

实际的复制操作是用<$完成的c $ c> savePDFFromInputFile 功能。此函数接受四个参数,您可以使用它们基本上控制目标以及如何命名复制的pdf文件。它检查它是否为pdf,获取它的原始文件名(您可以在之后使用)并创建一个 Blob ,其中包含来自FileReader的二进制数组结果。

The actual copy-operation is done with the savePDFFromInputFile function. This function accepts four params with which you can basically control the destination and how this copied pdf-file should be named. It checks for whether its a pdf, gets it's original filename (you can use afterwards) and creates a Blob which contains a binary-Array result from the FileReader.

但是在复制输入#文件之前,会创建一个新的空文件。之后,刚创建的 Blob 将写入此空文件。完成!

But before a input#file can be copied, a new empty file is created. After that the just created Blob is written to this empty file. Finish!

function savePDFFromInputFile(inputHTMLElement, appURI, sourcename, callback) {
   // check whether its a pdf
   if (inputHTMLElement.files[0] && 
       inputHTMLElement.files[0].type && 
       inputHTMLElement.files[0].type.indexOf('pdf') !== - 1) {
        var filename = "";
        var reader = new FileReader();
        var fullPath = inputHTMLElement.value;
        if (fullPath) {
            // get original filename that can be used in the callback
            var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\')  : fullPath.lastIndexOf('/'));
            var filename = fullPath.substring(startIndex);
            if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
                filename = filename.substring(1);
            }
        }
        reader.onload = function () {
            // the pdf-file is read as array-buffer 
            // this array-buffer can be put into a blob
            var blob = new Blob([reader.result], {
                type: 'application/pdf'
            });
            // create empty file
            $cordovaFile.createFile(appURI, sourcename, true).then(function (success) {
                // write to this empty file
                $cordovaFile.writeExistingFile(appURI, sourcename, blob, true).then(function (success) {
                    callback({
                        name: filename,
                        source: sourcename
                    });
                }, function (error) {
                    console.log(error);
                });
            }, function (error) {
                console.log(error);
            });
        };
        reader.readAsArrayBuffer(inputHTMLElement.files[0]);
   }
}

这是两个函数如何使用的示例:

This is an example of how both functions can be used:

// test for android-plattform
var isAndroid = true;
getAppURI(isAndroid, function(appURI){
    var inputFileElement = $('ID OR CLASS OF INPUT#FILE')[0]; // or use document.getElementById(...)
    var sourcename = (new Date()).getTime() + '.pdf';
    savePDFFromInputFile(inputFileElement, appURI, sourcename, function(copiedPDF){
        console.log("pdf copied successfully",copiedPDF.name,copiedPDF.source);
    });
});

希望有所帮助!

这篇关于Cordova从input type =&quot; file&quot;将文件保存到文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆