科尔多瓦将文件从输入类型保存到文件系统= "file"



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

谢谢!

希望你还在寻找答案。

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

函数getAppURI用于获取您可以将文件复制到的实际应用程序文件夹名称,它请求应用程序的缓存文件夹,并替换最后一个子文件夹名称以获取应用程序的基本uri,非常简单。

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

实际的复制操作是使用savePDFFromInputFile功能完成的。此函数接受四个参数,使用这些参数可以基本上控制目的地以及复制的pdf文件的命名方式。它检查它是否是pdf,获取它的原始文件名(以后可以使用),并创建一个Blob,其中包含FileReader的二进制数组结果。

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

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

这是如何使用这两种功能的示例:

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

希望它能有所帮助!

这样想可能会有所帮助:https://github.com/apache/cordova-plugin-file-transfer

最新更新