ParseFile javascript - saved as bytes - javascript

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

Related

How would I convert an image to base64 in reactJS

I have this function where I call a function and have a local file as the parameter to convert it to base64.
export const fileToBase64 = (filename, filepath) => {
return new Promise(resolve => {
var file = new File([filename], filepath);
var reader = new FileReader();
// Read file content on file loaded event
reader.onload = function(event) {
resolve(event.target.result);
};
// Convert data to base64
reader.readAsDataURL(file);
});
}
Importing the function
fileToBase64("shield.png", "./form").then(result => {
console.log(result);
console.log("here");
});
gives me an output as
data:application/octet-stream;base64,c2hpZWxkLnBuZw==
here
I want base64 information, but noticing the file the application/octet-stream is wrong? I entered an image so shouldn't it be
data:image/pgn;base64,c2hpZWxkLnBuZw==
https://medium.com/#simmibadhan/converting-file-to-base64-on-javascript-client-side-b2dfdfed75f6
try this I think this should helpfull
let buff = new Buffer(result, 'base64');
let text = buff.toString('ascii');
console.log(text)

Download file converted from Blob

In Javascript, test browser is Firefox. I have converted files to an array of bytes to store on my server and have used the subsequent code to convert the bytes back to a file, but I am unsure as to how to download the newly created file with appropriate file type can anyone please direct me?
to blob
$('input[type="file"]').change(function(e){
function convertFile(file){
return Array.prototype.map.call(new Uint8Array(file), x => ('00' + x.toString(16)).slice(-2)).join('');
}
file = event.target.files[0];
fileName = file.name;
fileSplit = fileName.split('.');
last = fileSplit.length-1;
let fileType = fileSplit[last];
$('#FileNameVisible').text(fileName);
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
fileData = e.target.result;
fileData = convertFile(e.target.result);
console.log(fileData);
};
reader.onerror = function() {
console.log(reader.error);
};
});
from Blob
var file = new File([dataUse], "File", {lastModified: Date.now()});
console.log(file);

File Getting Corrupted after upload node FS

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

How to Upload an Excel File in SAPUI5?

so I have this app where I upload a csv file using FileUploader. However now my requirement is to also allow excel files. The problem is that FileUploader doesn't support excel as it reads garbage. This is my attempt at parsing an excel file based on this example http://oss.sheetjs.com/js-xlsx/
Code:
var fileUpload = this.getView().byId("fileUploader");
var domRef = fileUpload.getFocusDomRef();
var file = domRef.files[0];
var XLSX = new ExcelPlus();
XLSX.createFile(["CT_MAIN"]);
var reader = new FileReader();
reader.onload = function(e) {
var strCSV = e.target.result;
var arr = String.fromCharCode.apply(null, new
Uint8Array(strCSV));
// var arr = fixData(strCSV);
console.log('data');
console.log(arr);
var workbook = XLSX.read(arr, {type : 'base64'});
console.log('output');
console.log(workbook);
//var output = toCsv(workbook);
//each one of the rows in the csv file
//var rows = arr;//strCSV.split("\n");
var rows = arr.split("\n");
.....
};
//reader.readAsText(file);
reader.readAsArrayBuffer(file);
//reader.readAsBinaryString(file);
If I upload a csv file using this code everything works fine. If I use an excel file I get the following
[1][Content_Types].xml ¢ [1]( [1]¬”ËNÃ0E÷HüCä-Jܲ#5í‚Ç Q>Àēƪc[žiiÿž‰ûB¡ j7± ÏÜ{2ñÍh²nm¶‚ˆÆ»R‹ÈÀU^7/ÅÇì%¿’rZYï #1__f›˜q·ÃR4DáAJ¬h >€ãÚÇV ßƹ
ªZ¨9ÈÛÁàNVÞ 8Ê©ÓãÑ Ôji){^óã-I‹"{Üv^¥P!XS)bR¹rú—K¾s(¸3Õ`c[1]Þ0†½
ÝÎß»¾7 M4²©ŠôªZÆk+¿|\|z¿(Ž‹ôPúº6 h_-[ž#!‚ÒØPk‹´¬2nÏ}Ä? £LËð Ýû%á ÄßdºždN"m,à¥ÇžDO97‚~§Èɸ8ÀOíc |n¦Ñä Eøÿ ö éºóÀBÉÀ!$}‡íàÈé;{ìÐå[ƒîñ–é2þÿÿ
what am I doing wrong, or what am I missing here?
Edit: after doing var workbook = XLSX.read(arr, {type : 'base64'}); I get null for both file types. The above garbage log comes from console.log(arr);
Since you are getting the file from the domRef you wouldn't need ExcelPlus. You just need to read the file as a binary string using xlsx. You will have to include the xlsx.full.min.js in your script.
var fileUpload = this.getView().byId("fileUploader");
var domRef = fileUpload.getFocusDomRef();
var file = domRef.files[0];
//var XLSX = new ExcelPlus();
//XLSX.createFile(["CT_MAIN"]);
var reader = new FileReader();
var name = file.name;
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, { type: 'binary' });
var result = {};
workbook.SheetNames.forEach(function (sheetName) {
var rObjArr = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if (rObjArr.length > 0) {
result[sheetName] = rObjArr;
}
});
var output = JSON.stringify(result, 2, 2);
console.log('output');
console.log(output);
};
reader.readAsBinaryString(file);

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

Categories

Resources