这并不完全是OP的场景,而是对一些评论者的答案。它是一个基于Cordova和Angular 1的解决方案,应该可以适应jQuery等其他框架。它为您提供了来自Base64数据的Blob,您可以将其存储在某个地方,并从客户端javascript / html引用它。
它还回答了有关如何从 Base 64 数据获取图像(文件)的原始问题:
重要的部分是 Base 64 - 二进制转换:
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
需要切片以避免内存不足错误。
适用于jpg和pdf文件(至少这是我测试的内容)。也应该与其他 mimetype/contenttypes 一起使用。检查您目标的浏览器及其版本,它们需要支持Uint8Array,Blob和atob。
以下是使用Cordova / Android将文件写入设备本地存储的代码:
...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
// Setup filename and assume a jpg file
var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
// attachment.document holds the base 64 data at this moment
var binary = base64toBlob(attachment.document, attachment.mimetype);
writeFile(fileEntry, binary).then(function() {
// Store file url for later reference, base 64 data is no longer required
attachment.document = fileEntry.nativeURL;
}, function(error) {
WL.Logger.error("Error writing local file: " + error);
reject(error.code);
});
}, function(errorCreateFile) {
WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
reject(errorCreateFile.code);
});
}, function(errorCreateFS) {
WL.Logger.error("Error getting filesystem: " + errorCreateFS);
reject(errorCreateFS.code);
});
...
写入文件本身:
function writeFile(fileEntry, dataObj) {
return $q(function(resolve, reject) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function() {
WL.Logger.debug(LOG_PREFIX + "Successful file write...");
resolve();
};
fileWriter.onerror = function(e) {
WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
reject(e);
};
// If data object is not passed in,
// create a new Blob instead.
if (!dataObj) {
dataObj = new Blob(['missing data'], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
})
}
我正在使用最新的Cordova(6.5.0)和插件版本:
我希望这能使在座的每个人都朝着正确的方向前进。