File Getting Corrupted after upload node FS - javascript

Hi i am using html5 filereader and node fs to upload the file to server which i am able to do so far, but the result file is larger than the original one.
here is my code.
var f = document.getElementById('file').files[0],
r = new FileReader();
console.log(f); //for checking file info
r.onloadend = function(e) {
var data = e.target.result;
var fs = require('fs');
try {
fs.writeFileSync(f.name, data, 'utf-8');
console.log('saved sucessfully!');
} catch (e) {
alert('Failed to save the file !');
}
}
r.readAsBinaryString(f);
}

Got it to work. I had to just convert data as ArrayBuffer
here is my final working code:
var fs = require('fs');
var f = document.getElementById('file').files[0],
r = new FileReader();
// console.log('srcPath='+f.path);
// console.log('savPath='+f.name);
r.onloadend = function(e) {
var data = e.target.result;
try {
fs.writeFileSync('uploads/' + f.name, Buffer.from(new Uint8Array(this.result)));
console.log('saved sucessfully!');
} catch (e) {
alert('Failed to save the file !');
}
//send your binary data via $http or $resource or do anything else with it
}
r.readAsArrayBuffer(f);
console.log('binary=' + r);

Related

HTTP Error 405.0 - Method Not Allowed with Put when attempting to upload a file

My previously working update function now returns a 405 error when it is run. This is after I added the fileReader functionality to facilitate file uploading for a pictures. How could I now have a HTTP verb error (which is what 405 is to my understanding) if my ajaxCall is untouched from it's working form?
function update()
{
//picture specific upload stuff
var reader = new FileReader();
var file = $('#fileUpload')[0].files[0];
reader.readAsBinaryString(file);
//What is readerEvt?
reader.onload = function (readerEvt)
{
//get binary data then convert to encoded string
var binaryString = reader.result;
var encodedString = btoa(binaryString);
//normal update fields
emp = new Object();
emp.Title = $("#TextBoxTitle").val();
emp.Firstname = $("#TextBoxFirstname").val();
emp.Lastname = $("#TextBoxLastname").val();
emp.Phoneno = $("#TextBoxPhone").val();
emp.Email = $("#TextBoxEmail").val();
emp.StaffPicture64 = encodedString;
emp.Id = localStorage.getItem("Id");
emp.DepartmentId = localStorage.getItem("DepartmentId");
emp.Version = localStorage.getItem("Version");
}
ajaxCall("Put", "api/employees", emp)
.done(function (data) {
$("#myModal").modal("hide");
getAll(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
return false;
}

Firebase Storage: "Invalid argument in put at index 0: Expected Blob or File

I keep getting an Invalid argument in put at index 0: Expected Blob or File error. The funny thing is the argument is totally a file...
Here is the code:
var file = document.getElementById('cke_69_fileInput')
.contentWindow.document.getElementById('cke_69_fileInput_input').files[0];
var storageUrl = 'noticias/imagenes/';
var storageRef = firebase.storage().ref(storageUrl + file.name);
console.warn(file); // Watch Screenshot
var uploadTask = storageRef.put(file);
Here's the screenshot of the actual file warn just before the error asking for a file...
try converting file to blob...
var reader = new FileReader();
reader.onloadend = function (evt) {
var blob = new Blob([evt.target.result], { type: "image/jpeg" });
var storageUrl = 'noticias/imagenes/';
var storageRef = firebase.storage().ref(storageUrl + file.name);
console.warn(file); // Watch Screenshot
var uploadTask = storageRef.put(blob);
}
reader.onerror = function (e) {
console.log("Failed file read: " + e.toString());
};
reader.readAsArrayBuffer(file);

ParseFile javascript - saved as bytes

I'm trying to save PDF file as ParseFile using Parse javascript SDK:
HTML
<input type="file" id="profilePhotoFileUpload" onchange="selectFile(event)">
JS
function selectFile(e) {
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var parseFile = new Parse.File("doc.pdf", file);
parseFile.save().then(function(){
var test = new Parse.Object("TestObject");
test.set("file",parseFile);
test.save();
}, function(error) {
});
}
and i'm getting bytes result as:
http://files.parsetfss.com/637e62db-7116-473c-97dc-48ad15ce73ca/tfss-f5f522d0-0634-4e98-9f2a-be659e5dac00-asdasdas.pdf
any solution?
SOLVED
default file data is Text.
i used FileReader to get data as base64 and then i save data like this:
fr = new FileReader();
fr.onload = receivedText;
fr.readAsDataURL(file);
function receivedText() {
result = fr.result;
var res = result.split("base64,");
var name = "myFile.pdf";
var parseFile = new Parse.File(name, { base64: res[1] });
parseFile.save().then(function() {
console.log("object saved!");
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
}

Get base64 of audio data from Cordova Capture

I am using ngCordova Capture to write this code by recording audio and send the base64 somewhere (via REST). I could get the Capture Audio to work but once it returns the audioURI, I cannot get the data from the filesystem as base64. My code is below:
$cordovaCapture.captureAudio(options).then(function(audioURI) {
$scope.post.tracId = $scope.tracId;
$scope.post.type = 'audio';
console.log('audioURI:');
console.log(audioURI);
var path = audioURI[0].localURL;
console.log('path:');
console.log(path);
window.resolveLocalFileSystemURL(path, function(fileObj) {
var reader = new FileReader();
console.log('fileObj:');
console.log(fileObj);
reader.onloadend = function (event) {
console.log('reader.result:');
console.log(reader.result);
console.log('event.result:');
console.log(event.result);
}
reader.onload = function(event2) {
console.log('event2.result:');
console.log(event2.target.result);
};
reader.readAsDataURL(fileObj);
console.log(fileObj.filesystem.root.nativeURL + ' ' + fileObj.name);
$cordovaFile.readAsDataURL(fileObj.filesystem.root.nativeURL, fileObj.name)
.then(function (success) {
console.log('success:');
console.log(success);
}, function (error) {
// error
});
});
Here is the output in console log:
So how do I get the base64 data from the .wav file?
I have been reading these links:
PhoneGap FileReader/readAsDataURL Not Triggering Callbacks
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
http://jsfiddle.net/eliseosoto/JHQnk/
http://community.phonegap.com/nitobi/topics/filereader_onload_not_working_with_phonegap_build_2_5_0
Had same problem, which I fixed using both the Cordova Capture and Cordova File plugin.
navigator.device.capture.captureAudio(function (audioFiles) {
var audioFile = audioFiles[0],
fileReader = new FileReader(),
file;
fileReader.onload = function (readerEvt) {
var base64 = readerEvt.target.result;
};
//fileReader.reasAsDataURL(audioFile); //This will result in your problem.
file = new window.File(audioFile.name, audioFile.localURL,
audioFile.type, audioFile.lastModifiedDate, audioFile.size);
fileReader.readAsDataURL(file); //This will result in the solution.
});

FileReader.readAsDataURL upload to express.js

I have the following code to upload to my Node.js/Express.js backend.
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var result = http.post('/files', e.target.result);
result.success(function () {
alert('done'):
});
}
My route looks like:
app.post('/files', function (req, res) {
var cws = fs.createWriteStream(__dirname + '/media/file');
req.pipe(cws);
res.send('success');
});
When I open /media/file with an image app I get a warning that it cannot read it. When I open the image file with a text-editor I see the base64 encoded string inside. Do I need to convert the string first before writing it to desk?
The problem was that a DataURL is prepended by meta data. You first need to remove that part before you create a base64 buffer.
var data_url = req.body.file;
var matches = data_url.match(/^data:.+\/(.+);base64,(.*)$/);
var ext = matches[1];
var base64_data = matches[2];
var buffer = new Buffer(base64_data, 'base64');
fs.writeFile(__dirname + '/media/file', buffer, function (err) {
res.send('success');
});
Got most code from this question.

Categories

Resources