XMPP File Transfer via JavaScript Strophe.js in Openfire - javascript

I am trying to get Strophe.js based XMPP file transfer to work. I can get logged in to work on my openfire server. I can send messages and receive messages fine but I am having trouble with file transfer.
HTML:
<form name='file_form' class="panel-body">
<input type="file" id="file" name="file[]" />
<input type='button' id='btnSendFile' value='sendFile' />
<output id="list"></output>
</form>
Javascript file:
// file
var sid = null;
var chunksize;
var data;
var file = null;
var aFileParts, mimeFile, fileName;
function sendFileClick() {
file =$("#file")[0].files[0];
sendFile(file);
readAll(file, function(data) {
log("handleFileSelect:");
log(" >data="+data);
log(" >data.len="+data.length);
});
}
function sendFile(file) {
var to = $('#to').get(0).value;
var filename = file.name;
var filesize = file.size;
var mime = file.type;
chunksize = filesize;
sid = connection._proto.sid;
log('sendFile: to=' + to);
// send a stream initiation
connection.si_filetransfer.send(to, sid, filename, filesize, mime, function(err) {
fileTransferHandler(file, err);
});
}
function fileTransferHandler(file, err) {
log("fileTransferHandler: err=" + err);
if (err) {
return console.log(err);
}
var to = $('#to').get(0).value;
chunksize = file.size;
chunksize = 20 * 1024;
// successfully initiated the transfer, now open the band
connection.ibb.open(to, sid, chunksize, function(err) {
log("ibb.open: err=" + err);
if (err) {
return console.log(err);
}
readChunks(file, function(data, seq) {
sendData(to, seq, data);
});
});
}
function readAll(file, cb) {
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
cb(evt.target.result);
}
};
reader.readAsDataURL(file);
}
function readChunks(file, callback) {
var fileSize = file.size;
var chunkSize = 20 * 1024; // bytes
var offset = 0;
var block = null;
var seq = 0;
var foo = function(evt) {
if (evt.target.error === null) {
offset += chunkSize; //evt.target.result.length;
seq++;
callback(evt.target.result, seq); // callback for handling read chunk
} else {
console.log("Read error: " + evt.target.error);
return;
}
if (offset >= fileSize) {
console.log("Done reading file");
return;
}
block(offset, chunkSize, file);
}
block = function(_offset, length, _file) {
log("_block: length=" + length + ", _offset=" + _offset);
var r = new FileReader();
var blob = _file.slice(_offset, length + _offset);
r.onload = foo;
r.readAsDataURL(blob);
}
block(offset, chunkSize, file);
}
function sendData(to, seq, data) {
// stream is open, start sending chunks of data
connection.ibb.data(to, sid, seq, data, function(err) {
log("ibb.data: err=" + err);
if (err) {
return console.log(err);
}
// ... repeat calling data
// keep sending until you're ready you've reached the end of the file
connection.ibb.close(to, sid, function(err) {
log("ibb.close: err=" + err);
if (err) {
return console.log(err);
}
// done
});
});
}
$('#btnSendFile').bind('click', function() {
console.log('File clicked:');
sendFileClick();
});
Full code is based on:
Complete example of Strophe.js file transfer
http://plnkr.co/edit/fYpXo1mFRWPxrLlgr123 (source can be download here: has errors). I changed the sendFileClick function.
I am getting:
ibb.open: err=Error: feature-not-implemented? Why is this error I am getting?

Related

form data going as null to HttpContext.Current.Request [duplicate]

This question already has an answer here:
How to POST binary files with AngularJS (with upload DEMO)
(1 answer)
Closed 4 years ago.
I have a file upload module.its working well with postman with no content type.but in code always file count is getting as 0 in backend api.if anyone knows what i am doing wrong,please help me. thanks
here is my back end api`
public async Task<HttpResponseMessage> PostUserImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 1 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Image/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
}
}
var message1 = string.Format("Image Updated Successfully.");
return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
var res = string.Format("some Message");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
}`
this is what i am getting after posting through postman
and this is what i am getting in my developer console.
my angular service foe uploading`
uploadimage:function(file,operation){
var deferred = $q.defer();
var httpReq = {
method: operation,
url: '/API/Customers/PostUserImage',
data:file,
transformRequest: angular.identity,
headers: {
'content-type': 'multipart/form-data'
},
onSuccess: function (response, status) {
deferred.resolve(response);
},
onError: function (response) {
deferred.reject(response);
}
};
httpService.call(httpReq);
return deferred.promise;
}`
this the controller code for appending to form data`
function readURL(input) {
debugger;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').css('background-image', 'url('+e.target.result +')');
$('#imagePreview').hide();
$('#imagePreview').fadeIn(650);
}
reader.readAsDataURL(input.files[0]);
var filesformdata = new FormData();
angular.forEach(input.files, function (value, key) {
filesformdata.append(key, value);
});
for (var pair of filesformdata.entries()) {
console.log(pair[0] + ', ' + pair[1]);
console.log(pair[1]);
}
profileService.uploadimage(filesformdata,"POST").then(function(response){
toastr.success("profilepicture changed");
});
}
}
and here is http request `
use API like
public async Task<HttpResponseMessage> MethodName()
{
if (HttpContext.Current.Request.ContentType == "application/x-www-form-urlencoded")
{
var ParameterName = int.Parse(HttpContext.Current.Request.Form.GetValues("ParameterName")[0].ToString());
}
else
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
}
var response = Request.CreateResponse(objreturn);
return response;
}
When sending non-alphanumeric file or big payload, you should be using form enctype attribute value of "multipart/form-data".
<form enctype="multipart/form-data" ...
Example: HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}

aws-sdk get file information

i am trying to get the file information from a file on my Amazon S3 server using the aws-sdk node module.
What i want to get out is the file name, file type and size.
I have attempted the following methods without luck:
s3.headObject(params, function (err, data) {
if (err) {
console.log(err, err.stack)
}
else {
d.resolve(data);
}
});
And
s3.getObject(params, function (err, data) {
if (err) {
console.log(err, err.stack)
}
else {
d.resolve(data);
}
});
Looking through their documentation i cant seem to find any other method that will give me the information i need.
So my question to you is how do i get the above information?
Here is the code to get the file name, size and content-type of all the objects present in a bucket.
Change the bucket name
Load your access keys from config.json accordingly
Code:-
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./config.json');
// Create S3 service object
s3 = new AWS.S3({ apiVersion: '2006-03-01' });
var bucketName = 'yourBucketName';
var params = {
Bucket: bucketName
};
var headParams = {
Bucket: bucketName
};
listAllKeys();
function listAllKeys() {
s3.listObjectsV2(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
var contents = data.Contents;
contents.forEach(function (content) {
//console.log(JSON.stringify(content));
headParams["Key"] = content.Key;
s3.headObject(headParams, function (err, headObjectData) {
if (err) {
console.log(err, err.stack);
} else {
console.log("1. File name :" + content.Key + ";" + " 2. File size :" + content.Size + ";" + " 3. Content-Type :" + headObjectData.ContentType);
}
});
});
if (data.IsTruncated) {
params.ContinuationToken = data.NextContinuationToken;
console.log("get further list...");
listAllKeys();
}
}
});
}
Sample output:-
1. File name :index.html; 2. File size :48; 3. Content-Type :text/html
s3.headObject works fine. You can find sample code below
let primaryBucket = primarys3bucketname;
var headParams = {
Bucket: primaryBucket,
};
let size = '';
headParams["Key"] = "/sample/path/to/filename.pdf";
s3.headObject(headParams).promise().then((headObjectData) => {
size = this.bytesToSize(headObjectData.ContentLength);
});
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

Node.js formidable file upload working slow on server

I am trying to send files as form data along with some fields using http post request in angular.js and receiving file in app.post in node.js. The file sending works fine on localhost. As they say formidable uploads files at 500 mb/sec speed but on server when I am trying to send a file of 5 to 10 mb it takes 40 to 80 seconds. Please check is there any problem in my implementation.
I am using nginx and pm2 on server.
Node.js code:
// route for uploading audio asynchronously
app.post('/v1/uploadAudio', function(req, res) {
var userName, useravatar, hasfile, ismusicfile, isType, showMe, DWimgsrc, DWid, msgtime;
var imgdatetimenow = Date.now();
var form = new formidable.IncomingForm({
uploadDir: __dirname + '/public/app/upload/music',
keepExtensions: true
});
form.on('end', function() {
res.end();
});
form.parse(req, function(err, fields, files) {
console.log("files : ", files);
console.log("fields : ", fields);
var data = {
username: fields.username,
userAvatar: fields.userAvatar,
repeatMsg: true,
hasFile: fields.hasFile,
isMusicFile: fields.isMusicFile,
istype: fields.istype,
showme: fields.showme,
dwimgsrc: fields.dwimgsrc,
dwid: fields.dwid,
serverfilename: baseName(files.file.path),
msgTime: fields.msgTime,
filename: files.file.name,
size: bytesToSize(files.file.size)
};
var audio_file = {
dwid: fields.dwid,
filename: files.file.name,
filetype: fields.istype,
serverfilename: baseName(files.file.path),
serverfilepath: files.file.path,
expirytime: imgdatetimenow + (120000)
};
files_array.push(audio_file);
ios.sockets.emit('new message music', data);
});
});
AngularJS code:
// =========================================== Audio Sending Code =====================
$scope.$watch('musicFiles', function() {
$scope.sendAudio($scope.musicFiles);
});
// opens the sent music file on music_icon click on new window
$scope.openClickMusic = function(msg) {
$http.post($rootScope.baseUrl + "/v1/getfile", msg).success(function(response) {
if (!response.isExpired) {
window.open($rootScope.baseUrl + '/' + response.serverfilename, "_blank");
} else {
var html = '<p id="alert">' + response.expmsg + '</p>';
if ($(".chat-box").has("p").length < 1) {
$(html).hide().prependTo(".chat-box").fadeIn(1500);
$('#alert').delay(1000).fadeOut('slow', function() {
$('#alert').remove();
});
}
}
});
}
// recieving new music message
$socket.on("new message music", function(data) {
if (data.username == $rootScope.username) {
data.ownMsg = true;
data.dwimgsrc = "app/images/spin.gif";
} else {
data.ownMsg = false;
}
if ((data.username == $rootScope.username) && data.repeatMsg) {
checkMessegesMusic(data);
} else {
$scope.messeges.push(data);
}
});
// replacing spinning wheel in sender message after music message delivered to everyone.
function checkMessegesMusic(msg) {
for (var i = ($scope.messeges.length - 1); i >= 0; i--) {
if ($scope.messeges[i].hasFile) {
if ($scope.messeges[i].istype === "music") {
if ($scope.messeges[i].dwid === msg.dwid) {
$scope.messeges[i].showme = true;
$scope.messeges[i].serverfilename = msg.serverfilename;
$scope.messeges[i].filename = msg.filename;
$scope.messeges[i].size = msg.size;
$scope.messeges[i].dwimgsrc = "app/images/musicplay_icon.png";
break;
}
}
}
};
}
// download music file if it exists on server else return error message
$scope.downloadMusic = function(ev, elem) {
var search_id = elem.id;
for (var i = ($scope.messeges.length - 1); i >= 0; i--) {
if ($scope.messeges[i].hasFile) {
if ($scope.messeges[i].istype === "music") {
if ($scope.messeges[i].dwid === search_id) {
$http.post($rootScope.baseUrl + "/v1/getfile", $scope.messeges[i]).success(function(response) {
if (!response.isExpired) {
var linkID = "#" + search_id + "A";
$(linkID).find('i').click();
return true;
} else {
var html = '<p id="alert">' + response.expmsg + '</p>';
if ($(".chat-box").has("p").length < 1) {
$(html).hide().prependTo(".chat-box").fadeIn(1500);
$('#alert').delay(1000).fadeOut('slow', function() {
$('#alert').remove();
});
}
return false;
}
});
break;
}
}
}
};
}
// validate file type to 'music file' function
$scope.validateMP3 = function(file) {
if (file.type == "audio/mp3" || file.type == "audio/mpeg") {
return true;
} else {
var html = '<p id="alert">Select MP3.</p>';
if ($(".chat-box").has("p").length < 1) {
$(html).hide().prependTo(".chat-box").fadeIn(1500);
$('#alert').delay(1000).fadeOut('slow', function() {
$('#alert').remove();
});
}
return false;
}
}
// sending new 'music file' function
$scope.sendAudio = function(files) {
if (files && files.length) {
$scope.isFileSelected = true;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var dateString = formatAMPM(new Date());
var DWid = $rootScope.username + "dwid" + Date.now();
var audio = {
username: $rootScope.username,
userAvatar: $rootScope.userAvatar,
hasFile: $scope.isFileSelected,
isMusicFile: true,
istype: "music",
showme: false,
dwimgsrc: "app/images/musicplay_icon.png",
dwid: DWid,
msgTime: dateString
}
$socket.emit('send-message', audio, function(data) { // sending new image message via socket
});
var fd = new FormData();
fd.append('file', file);
fd.append('username', $rootScope.username);
fd.append('userAvatar', $rootScope.userAvatar);
fd.append('hasFile', $scope.isFileSelected);
fd.append('isMusicFile', true);
fd.append('istype', "music");
fd.append('showme', false);
fd.append('dwimgsrc', "app/images/musicplay_icon.png");
fd.append('dwid', DWid);
fd.append('msgTime', dateString);
fd.append('filename', file.name);
$http.post('/v1/uploadAudio', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}).then(function(response) {
// console.log(response);
});
}
}
};
I've used Formidable on a couple of side projects, and when uploading to localhost, I do see the 500mb/sec quoted capability (depending on physical hardware of the computer).
However, when uploading a file over the internet, you are subject to the bandwidth limitations of your ISP upload speed as well as the download speed of your server.
You report that a 10MB file takes ~80 seconds to upload to the server. That's about 125KBps (or around 1 megabit/second) which seems fairly reasonable for a home/office ISP upload speed (depending on region of the world).
A good way to eliminate your home/office network performance from the troubleshooting equation would be to write a node.js script that uploads a file several times and calculates an average speed. Run that test file on your local computer, then try again from a different server in the cloud.

Uploading video without 777 does not work

I am locally testing my node video upload. my upload class looks like this:
var videoExtensions = ['mp4', 'webm', 'mov'];
var audioExtensions = [];
//Media object
function Media(file, targetDirectory) {
this.file = file;
this.targetDir = targetDirectory;
}
Media.prototype.isVideo = function () {
return this.file.mimetype.indexOf('video') >= 0;
};
Media.prototype.isAudio = function () {
return this.file.mimetype.indexOf('audio') >= 0;
};
Media.prototype.getName = function () {
return this.file.originalname.substr(0, this.file.originalname.indexOf('.'))
};
router.route('/moduleUpload')
.post(function (request, response) {
var media = new Media(request.files.file, '../user_resources/module/' + request.body.module_id + '/');
if (!fs.existsSync(media.targetDir)) {
fs.mkdirSync(media.targetDir, 0777, function (err) {
if (err) {
console.log(err);
response.send("ERROR! Can't make the directory! \n"); // echo the result back
}
});
}
if (media.isVideo()) {
convertVideos(media);
}
else if (media.isAudio()) {
convertAudio(media);
}
else {
moveFile(media);
}
response.status(200).json('user_resources/module/' + request.body.module_id + '/' + media.getName());
});
router.route('/retrieveFile')
.post(function (request, response) {
var path = '../' + request.body.data;
var file = fs.createReadStream(path);
file.pipe(response);
});
function convertVideos(media) {
var ffmpeg = require('fluent-ffmpeg');
videoExtensions.forEach(function (extension) {
var proc = new ffmpeg({source: media.file.path, nolog: false})
.withVideoCodec('libx264')
.withVideoBitrate(800)
.withAudioCodec('libvo_aacenc')
.withAudioBitrate('128k')
.withAudioChannels(2)
.toFormat(extension)
.saveToFile(media.targetDir + media.getName() + '.' + extension,
function (retcode, error) {
console.log('file has been converted succesfully');
});
});
}
function convertAudio(media) {
var ffmpeg = require('fluent-ffmpeg');
audioExtensions.forEach(function (extension) {
var proc = new ffmpeg({source: media.file.path, nolog: false})
.withVideoCodec('libx264')
.withVideoBitrate(800)
.withAudioCodec('libvo_aacenc')
.withAudioBitrate('128k')
.withAudioChannels(2)
.toFormat(extension)
.saveToFile(media.targetDir + media.getName() + '.' + extension,
function (retcode, error) {
console.log('file has been converted succesfully');
});
});
}
When a video file is uploaded it is convert into 3 different files.
Now the file i wish to upload is in my /Video folder at first this did not have any permissions. Which resulted in the upload could not play. However as soon as i changed the permission of the file to 777 the video plays without a problem.
My question is why? am i missing something in my upload and is chmod 777 wise?
also note im using ubuntu 14.04

Merging multiple parts of a file in Cordova

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!
you can build a blob from other blobs, like the ones you use FileReader on now. (File()s are Blobs)
// put three blobs into a fourth:
var b=new Blob([new Blob(["hello"]), new Blob([" "]), new Blob(["world"])]);
// verify the blob has the data we expect:
var fr=new FileReader();
fr.onload=function(){alert(this.result);};
fr.readAsBinaryString(b); // shows: "hello world"
the binaryString flavor is used here to show how these low-order strings stack up, but the actual new blob instance should have all the orig (arbitrary) bytes from the original blobs, even if they aren't composed of simple strings...
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.

Categories

Resources