So I am trying to print a Base64 file but im not sure why it doesn't print the file.
function convertToBase64() {
var selectedFile = document.getElementById("inputFile").files;
if (selectedFile.length > 0) {
var fileToLoad = selectedFile[0];
var fileReader = new FileReader();
var base64;
fileReader.onload = function (fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
const pdfBlob = new Blob([base64], { type: "application/pdf" });
const url = URL.createObjectURL(pdfBlob);
printJS({
printable: url,
type: "pdf",
base64: true
});
};
fileReader.readAsDataURL(fileToLoad);
}
}
I pass it a pdf file that I select and convert it to Base64.Now I want to print the Base64 using Print.js but I can't make it work.
Your code isn't actually passing the base64 data to the print function, but instead, a URL.
If you want to keep your current code, just remove the base64 flag from the print params.
printJS({
printable: url,
type: 'pdf',
});
Otherwise, you could instead just pass the base64 var to the print function without creating the blog and url, the print library will handle that for you.
Ex.:
Assuming base64Data is a variable with valid base64 data.
printJS({
printable: base64Data,
type: 'pdf',
base64: true
});
Related
I am downloading a file from the web, I need to save him in the file cabinet, but when I save it its an empty file (0kb).
let response = https.get({
url: url
});
log.debug('response', JSON.stringify(response.body)) //getting the file content
let fileContent = response.body;
let decodedStr = fileToBase64(fileContent); // get base64 content
let createFile = file.create({
name: "test.csv",
fileType: file.Type.CSV,
content: decodedStr,
folder: 1000
});
createFile.save();
//get base 64
function fileToBase64(stringInput) {
return encode.convert({
string: stringInput,
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64
});
}
still gets an empty csv file.
I suspect if it base64Encoded the file type should not be CSV but file.Type.PLAINTEXT
I am using yeoman angular fullstack and im trying to do a simple file upload. I read the file from a form and i get it into the front end just fine
this.$scope.add = function() {
var f = document.getElementById('resume').files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
console.log(e.target.result);
Auth.saveResume({
data: e.target.result,
name:theFile.name
});
};
})(f);
reader.readAsArrayBuffer(f);
}
in auth.services.ts i have
saveResume(resume, callback?: Function) {
console.log(User)
return User.saveResume({ id: currentUser._id }, {resume},
function() {
console.log('auth.service in function');
console.log('currentUser._id: ' + currentUser._id);
return safeCb(callback)(null);
},
function(err) {
return safeCb(callback)(err);
}).$promise;
},
it successfully makes it into my back end controller
router.put('/:id/resume', auth.isAuthenticated(), controller.saveResume);
where i have a saveResume function
export function saveResume(req, res){
console.log(typeof req.body.resume.data);
console.log(typeof req.body.resume.name);
}
In the save resume function when i access the "name" parameter it is correct and is of type string. However when i access "data" i just get an object. I would like data to be either a file or buffer so i can upload it to s3.
My only guess for why its an object instead of an ArrayBuffer is that i think node doesnt support javascript ArrayBuffers, blobs, or files. How do i get the file in the backend in some form that s3 will accept? ie file, blob, or buffer
As #bubblez suggest i encoded it to base 64 like so
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
Auth.saveResume(f.name, base64);
};
// Convert data to base64
fileReader.readAsDataURL(f);
i also changed auth so that it takes two separate parameters
saveResume(name, data, callback?: Function) {
console.log(User)
return User.saveResume({ id: currentUser._id }, {name, data},
function() {
console.log('auth.service in function');
console.log('currentUser._id: ' + currentUser._id);
return safeCb(callback)(null);
},
function(err) {
return safeCb(callback)(err);
}).$promise;
},
i then decode from base 64
export function saveResume(req, res){
var base64String = req.body.data.split(';base64,').pop();
console.log(base64String);
var buf = Buffer.from(base64String, 'base64').toString('utf');
uploadParams.Body = buf;
}
and this works!
I am trying to JSONify a blob file so that I can send it over AJAX requests. I have tried with the code below without any success. When I parse a JSONified file, I only get a different file with much smaller size.
function test(blob, cb) {
var fileReader = new FileReader()
fileReader.readAsArrayBuffer(blob)
fileReader.onloadend = function() {
// client
var arry = Array.from(new Uint8Array(fileReader.result))
var data = {data: arry }
var json = JSON.stringify(data)
// server
var parse = JSON.parse(json)
var arr = parse.data.buffer
var blob = new Blob([arr])
}
}
You can try to use FileReader.readAsDataURL() method, and send the data as base64 encoded string, and than decode it on the server side. Base64 string will be much smaller than json string representing an array.
Here is an example
function getBase64() {
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
document.getElementById("result").value = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<input type="file" onchange="getBase64()" />
<br/>
<textarea id="result"></textarea>
You can use FormData.
JQuery example (for simplicity):
var oFormData = new FormData();
$(':input', this).each(function (){
if(this.name){
var oValue = this.value;
if(this.type == 'file'){
oValue = this.files[0]; //TODO if "input file multiple" need loop each value
}
oFormData.append(this.name, oValue);
}
});
$.ajax({
url: 'http://example.com/xhr',
type: "POST",
data: oFormData,
processData: false,
contentType: false,
error: function (oRequest, sTextStatus, oErrorThrown){
console.log(sTextStatus);
},
success: function (oData, sTextStatus, oRequest){
console.log(oData);
},
});
I whant to write a Cordova App for BlackBerry10 that can write a PDF file (from a SharePointWebservice) and show it.
The PDF is transmitted from a ASP.NET Webservice as byte[] using
byte[] result = spFile.OpenBinary();
I'm able to access the file with JSON. This works fine.
To transform the data fromm JSON to usable format I use the following code:
var binary = '';
var bytes = new Uint8Array(data.d);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(data.d[i]);
}
binary is now looking like that:
%PDF-1.5%ยตยตยตยต 1 0 obj ... startxref 103423 %%EOF
Here is the Code to write it to a file using cordova-plugin-file.
var blob = new Blob([binary], { type: 'application/pdf' });
fileWriter.write(blob);
It works fine for txt files, but when I try to write the PDF file I get an empty document.
I have also tryed window.btoa(binary) instead of just using binary.
Any ideas what ho to create the data blob, or which format to use?
I have solved the Problem by using the cordova fileOpener2 Plugin. I am using the var "bytes" from above filled into the new named variable data.
try {
window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
directoryEntry.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
cordova.plugins.fileOpener2.open(cordova.file.externalApplicationStorageDirectory + fileName, 'application/pdf',
{
error: function (e) {
...
},
success: function () {
... //PDF has opened
}
}
);
};
fileWriter.onerror = function (e) {
...
};
//Blob erstellen - Blackberry File Plugin verwenden
var blob = new Blob([data], { type: 'application/pdf' });
fileWriter.write(blob);
}, function onerror(e) {
...
});
}, function onerror(e) {
...
});
}, function onerror(e) {
...
});
} catch (e) {
...
}
Used Plugins:
cordova-plugin-file &
cordova-plugin-file-opener2
For other file types like PNG I use (for jpg just replace png with jpg):
var blob = new Blob([data], { type: 'image/png' });
to write the file and
window.open(cordova.file.externalApplicationStorageDirectory + fileName);
to open and show it.
Showing txt files is quite easy, you can do it like that:
if (fileName.split('.')[1].indexOf("txt") > -1) {
var blob = new Blob([bytes], { type: 'text/plain' });
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
This worked for me, comment if you have any questions.
I'm trying to download a group of image files that I am retrieving from Parse and save them to a zip file using JSZip. From this link it seems like I should be able to get the base64 encoding just by calling .base64 on my image object. I also tried toString('base64'). My zip file generates with files of the correct names but the contents of the files are empty. Am I missing something here?
Parse.Cloud.httpRequest({ url: result.get('image').url() }).then(function(response) {
var image = new Image();
image.setData(response.buffer);
var base64Image = image.data().base64;
zip.folder('images').file(imageName, base64Image, {base64: true});
return Parse.Promise.as('Success')
})
Finally managed to solve it by treating image.data() as asynchronous:
Parse.Cloud.httpRequest({ url: result.get('image').url() }).then(function(response) {
var image = new Image();
image.setData(response.buffer);
return image.data().then(function(data) {
zip.folder('images').file(imageName, data.toString('base64'), {base64: true});
return Parse.Promise.as('Success');
});
})