在Cordova中合并文件的多个部分 [英] Merging multiple parts of a file in Cordova

查看:101
本文介绍了在Cordova中合并文件的多个部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Cordova应用程式中,我要下载任何档案,例如图片或影片档案。这是用Cordova文件传输插件和范围标题,因为我需要下载的部分文件。



我的问题是,我想要将几个小的Byte-Files合并回到原始文件,他们曾在哪里使用该文件。每次我试图通过FileReader读取作为binaryString的结果零件,并将它们一起写在一个新文件中,该文件结束比原始文件altogther的部分大得多,并且生成的文件不可用。



这里是我的代码直到现在(长和丑陋):

  document.addEventListener('deviceready',deviceready,false); 

var App;

var finishedFileUrl =;

var async = {
sequence:function(items,callback){
var def = $ .Deferred(),
deferrers = [$ .Deferred ];

for(var i = 0; i< items.length; i ++){
(function(n){
deferrers [n + 1] = $ .Deferred );
deferrers [n] .always(function(){
callback(items [n],deferrers [n + 1]);
});一世);
}
deferrers [items.length] .always(function(){
def.resolve();
});
deferrers [0] .resolve();

return def.promise();
}
}

var aSmallImageArray = [
''//使用Range Header请求的URL可以访问的URL
];

var aByteSizeImageArray = [];

function formatDownloadArray(fileSize){
for(var j = 1000; j <= fileSize; j + = 1000){
aByteSizeImageArray.push
}
aByteSizeImageArray.push(j);
}

function deviceready(){
console.log('dv ready');

function registerHandlers(){
App = new DownloadApp();
formatDownloadArray(XXXXX); // XXXXX应该是以字节为单位的JPG大小
document.getElementById(startDl)。onclick = function(){
var that = this;
console.log(load button clicked);
var folderName =testimagefolder;

//序列调用
async.sequence(aByteSizeImageArray,function(currentBytes,iter){
var filePath = aSmallImageArray [0];
var fileName = aSmallImageArray [ 0] .substr(52,99)+ currentBytes;
console.log(filePath);
console.log(fileName);
console.log(Starting with:+ fileName) ;
var uri = encodeURI(filePath);
var folderName =testimagefolder;
document.getElementById(statusPlace)。innerHTML =< br / uri;
App.load(currentBytes,uri,folderName,fileName,
function progress(percentage){
document.getElementById(statusPlace)。innerHTML =< br / + percentage +%;
},
function success(entry){
console.log(Entry:+ entry);
document.getElementById(statusPlace)。innerHTML =< br />图片已保存到:+ App.filedir;
console.log(DownloadApp.filedir:+ App.filedir);
iter.resolve();
},
function error(){
document.getElementById(statusPlace)。innerHTML =< br /> Failed load image:+ uri;
iter.resolve();
}
);
})。then(function afterAsync(){
console.log(ASYNC DONE);
var ohNoItFailed = function ohNoItFailed(exeperro){
console.log );
}
//现在我们将文件部分合并为一个文件以显示它
window.requestFileSystem(LocalFileSystem.PERSISTENT,0,function(FileSystem){
FileSystem.root .getDirectory(folderName,{create:true,exclusive:false},function itSuccessed(Directory){
Directory.getFile(aSmallImageArray [0] .substr(52,99),{create:true,exclusive: ,function itSuccessedAgain(fileEntry){
finishedFileUrl = fileEntry.toURL();
var directoryReader = Directory.createReader();
var allFiles = directoryReader.readEntries(function succesReadDir(fileEntries){
async.sequence(fileEntries,function(currentFile,iterThis){
currentFile.file(function(theActualFile){
var myFileReader = new FileReader();
myFileReader.onload = function(content){
console.log('FileReader onload event fired!');
console.log('File Content should be:'+ content.target.result);
fileEntry.createWriter(
function mergeImage(writer){
writer.onwrite = function(evnt){
console.log(Writing successful!);
iterThis.resolve();
}
writer.seek(writer.length);
writer.write(content.target.result);
},ohNoItFailed);
};
myFileReader.readAsBinaryString(theActualFile);
},ohNoItFailed);
})。then(function afterAsyncTwo(){
console.log(NOW THE IMAGE SHOULD BEKEN FROM THIS PATH:+ finishedFileUrl);

// window。 requestFileSystem(LocalFileSystem.PERSISTENT,0,function(FileSystem){
//FileSystem.root.getDirectory(folderName,{create:true,exclusive:false},function itSuccessed(Directory){
// Directory .getFile(aSmallImageArray [0] .substr(52,99),{create:true,exclusive:false},function itSuccessedAgain(fileEntry){
//fileEntry.createWriter(

document .getElementById(image_here)。src = finishedFileUrl;
});
},ohNoItFailed);
},ohNoItFailed);
},ohNoItFailed);
},ohNoItFailed);
});
};
}
registerHandlers();
}

var DownloadApp = function(){}

DownloadApp.prototype = {
filedir:,
load:function (currentBytes,uri,folderName,fileName,progress,success,fail){
var that = this;
that.progress = progress;
that.success = success;
that.fail = fail;
filePath =;

that.getFilesystem(
function(fileSystem){
console.log(GotFS);
that.getFolder(fileSystem,folderName,function {
filePath = folder.toURL()+ fileName;
console.log(FILEPATH:+ filePath);
console.log(URI:+ uri);
..transferFile(currentBytes,uri,filePath,progress,success,fail);
},function(error){
console.log(Failed to get folder:+ error.code);
typeof that.fail ==='function'&& amp; that.fail(error);
});
},
function(error){
console.log(Failed to get filesystem:+ error.code);
typeof that.fail ==='function'&& amp; that.fail(error);
}
);
},

getFilesystem:function(success,fail){
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT,0,success,fail);
},

getFolder:function(fileSystem,folderName,success,fail){
fileSystem.root.getDirectory(folderName,{create:true,exclusive:false},success ,fail)
},

transferFile:function(currentBytes,uri,filePath,progress,success,fail){
var that = this;
that.progress = progress;
that.success = success;
that.fail = fail;
console.log(here we go);
console.log(filePath before Request:+ filePath);

var previousBytes = currentBytes - 1000;

var transfer = new FileTransfer();
transfer.onprogress = function(progressEvent){
if(progressEvent.lengthComputable){
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
typeof that.progress ==='function'&&& .progress(perc); // increment for scale 0..100(percentage)as numbers
} else {
}
};

transfer.download(
uri,
filePath,
function success(entry){
console.log(File saved to:+ entry .toURL());
typeof that.success ==='function'&& that.success(entry);
},
function errorProblem(error){
console.log(发生错误:Code =+ error.code);
console.log(download error source+ error.source);
console.log target+ error.target);
console.log(下载错误代码+ error.code);
typeof that.fail ==='function'& );
},
true,
{
header:{
Range:bytes =+ previousBytes + - + currentBytes
}
}
);
}
}

通过stackoverflow-用户的异步代码:Paul Facklam
- >非常感谢。

解决方案

使用readAsArrayBuffer()而不是readAsBinaryString

所以代替:

  myFileReader.readAsBinaryString(theActualFile); 

我:

  myFileReader.readAsBinaryArray(theActualFile); 

生成的图片文件可用。


Within my Cordova app, I am downloading arbitrary files like images or video files. This is done with the Cordova file-transfer plugin and the "Range" Header, because I need to download the files in parts.

My Problem is, that I want to merge back the several small "Byte"-Files back together into the original file they once where to use that file. Every time I'm trying to read the resulting parts as binaryString via the FileReader and write them together in a new file, that file ends up a lot larger than the parts of the original file altogther and the resulting file is unusable.

Any help is appreciated.

Here is my code until now (long and ugly):

document.addEventListener('deviceready', deviceready, false);

var App;

var finishedFileUrl = "";

var async = {
    sequence: function(items, callback) {       
        var def = $.Deferred(),
        deferrers = [$.Deferred()];

        for(var i = 0; i < items.length; i++) {
            (function (n) {     
                deferrers[n + 1] = $.Deferred();
                deferrers[n].always(function() {
                    callback(items[n], deferrers[n + 1]);
                });
            })(i);  
        }
        deferrers[items.length].always(function() {
            def.resolve();
        });         
        deferrers[0].resolve();

        return def.promise();
    }
}

var aSmallImageArray = [
'' // Put URL to JPG accessible with Range Header Request here
];

var aByteSizeImageArray = [];

function formatDownloadArray(fileSize) {
    for(var j = 1000; j <= fileSize; j += 1000) {
        aByteSizeImageArray.push(j);
    }
    aByteSizeImageArray.push(j);
}

function deviceready() {
    console.log('dv ready');

    function registerHandlers() {
        App = new DownloadApp();
        formatDownloadArray(XXXXX);     // XXXXX should be size of JPG in bytes
        document.getElementById("startDl").onclick = function() {
            var that = this;
            console.log("load button clicked");
            var folderName = "testimagefolder";

            // sequence call
            async.sequence(aByteSizeImageArray, function(currentBytes, iter) {
                var filePath = aSmallImageArray[0];
                var fileName = aSmallImageArray[0].substr(52,99) + currentBytes;
                console.log(filePath);
                console.log(fileName);
                console.log("Starting with: " + fileName);
                var uri = encodeURI(filePath);
                var folderName = "testimagefolder";
                document.getElementById("statusPlace").innerHTML = "<br/>Loading: " + uri;
                App.load(currentBytes, uri, folderName, fileName,
                    function progress (percentage) {
                         document.getElementById("statusPlace").innerHTML = "<br/>" + percentage + "%";
                    },
                    function success (entry) {
                        console.log("Entry: " + entry);
                        document.getElementById("statusPlace").innerHTML = "<br/>Image saved to: " + App.filedir;
                        console.log("DownloadApp.filedir: " + App.filedir);
                        iter.resolve();
                    },
                    function error () {
                        document.getElementById("statusPlace").innerHTML = "<br/>Failed load image: " + uri;
                        iter.resolve();
                    }
                );              
            }).then(function afterAsync () {
                console.log("ASYNC DONE");
                var ohNoItFailed = function ohNoItFailed (exeperro) {
                    console.log(exeperro);
                }
                // now we merge the fileparts into one file to show it
                window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (FileSystem) {
                    FileSystem.root.getDirectory(folderName, {create: true, exclusive: false}, function itSuccessed (Directory) {
                        Directory.getFile(aSmallImageArray[0].substr(52,99), {create: true, exclusive: false}, function itSuccessedAgain (fileEntry) {
                            finishedFileUrl = fileEntry.toURL();
                            var directoryReader = Directory.createReader();
                            var allFiles = directoryReader.readEntries(function succesReadDir (fileEntries) {
                                async.sequence(fileEntries, function(currentFile, iterThis) {
                                    currentFile.file(function (theActualFile) {
                                        var myFileReader = new FileReader();
                                        myFileReader.onload = function (content) {
                                            console.log('FileReader onload event fired!');
                                            console.log('File Content should be: ' + content.target.result);
                                            fileEntry.createWriter(
                                            function mergeImage (writer) {
                                                writer.onwrite = function (evnt) {
                                                    console.log("Writing successful!");
                                                    iterThis.resolve();
                                                }
                                                writer.seek(writer.length);
                                                writer.write(content.target.result);
                                            }, ohNoItFailed);
                                        };
                                        myFileReader.readAsBinaryString(theActualFile);
                                    }, ohNoItFailed);
                                }).then(function afterAsyncTwo () {
                                    console.log("NOW THE IMAGE SHOULD BE TAKEN FROM THIS PATH: " + finishedFileUrl);

                                    //window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (FileSystem) {
                                        //FileSystem.root.getDirectory(folderName, {create: true, exclusive: false}, function itSuccessed (Directory) {
                                            //Directory.getFile(aSmallImageArray[0].substr(52,99), {create: true, exclusive: false}, function     itSuccessedAgain (fileEntry) {    
                                                //fileEntry.createWriter(    

                                        document.getElementById("image_here").src = finishedFileUrl;    
                                });    
                            }, ohNoItFailed);                               
                        }, ohNoItFailed);    
                    }, ohNoItFailed);    
                }, ohNoItFailed);                       
            });    
        };    
    }    
    registerHandlers();    
}    

var DownloadApp = function() {}

DownloadApp.prototype = {
    filedir: "",
    load: function(currentBytes, uri, folderName, fileName, progress, success, fail) {
        var that = this;
        that.progress = progress;
        that.success = success;
        that.fail = fail;
        filePath = "";

        that.getFilesystem(
                function(fileSystem) {
                    console.log("GotFS");
                    that.getFolder(fileSystem, folderName, function(folder) {
                        filePath = folder.toURL() + fileName;
                        console.log("FILEPATH: " + filePath);
                        console.log("URI: " + uri);
                        that.transferFile(currentBytes, uri, filePath, progress, success, fail);
                    }, function(error) {
                        console.log("Failed to get folder: " + error.code);
                        typeof that.fail === 'function' && that.fail(error);
                    });
                },
                function(error) {
                    console.log("Failed to get filesystem: " + error.code);
                    typeof that.fail === 'function' && that.fail(error);
                }
        );
    },

    getFilesystem: function (success, fail) {
        window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, fail);
    },

    getFolder: function (fileSystem, folderName, success, fail) {
        fileSystem.root.getDirectory(folderName, {create: true, exclusive: false}, success, fail)
    },

    transferFile: function (currentBytes, uri, filePath, progress, success, fail) {
        var that = this;
        that.progress = progress;
        that.success = success;
        that.fail = fail;
        console.log("here we go");
        console.log("filePath before Request: " + filePath);

        var previousBytes = currentBytes - 1000;

        var transfer = new FileTransfer();
        transfer.onprogress = function(progressEvent) {
            if (progressEvent.lengthComputable) {
                var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
                typeof that.progress === 'function' && that.progress(perc); // progression on scale 0..100 (percentage) as number
            } else {
            }
        };

        transfer.download(
            uri,
            filePath,
            function success (entry) {
                console.log("File saved to: " + entry.toURL());
                typeof that.success === 'function' && that.success(entry);
            },
            function errorProblem(error) {
                console.log("An error has occurred: Code = " + error.code);
                console.log("download error source " + error.source);
                console.log("download error target " + error.target);
                console.log("download error code " + error.code);
                typeof that.fail === 'function' && that.fail(error);
            },
            true,
            {
                headers: {
                    "Range": "bytes=" +  previousBytes + "-" + currentBytes
                }
            }
        );
    }
}   

async code by stackoverflow-user: Paul Facklam -> Thanks a lot!

解决方案

Using readAsArrayBuffer() instead of readAsBinaryString() did the trick!

So instead of:

myFileReader.readAsBinaryString(theActualFile);

I did:

myFileReader.readAsBinaryArray(theActualFile);

And the resulting image file is usable.

这篇关于在Cordova中合并文件的多个部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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