Cordova save file to filesystem from input type=“f

2019-08-14 15:36发布

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

Thanks!

2条回答
爷的心禁止访问
2楼-- · 2019-08-14 16:14
叼着烟拽天下
3楼-- · 2019-08-14 16:35

Hope, you are still looking for an answer.

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.

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);
        });
    }
}

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.

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);
    });
});

Hope it helps!

查看更多
登录 后发表回答