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');
});
})
Related
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
});
actually there are many answers for this question. But my problem is,
i want to generate pdf dynamically with 5 external(URL) images. Im using PDFmake node module.
it supports only two ways local and base64 format. But i don't want to store images locally.
so my requirement is one function which takes url as parameter and returns base64.
so that i can store in global variable and create pdfs
thanks in advance
function urlToBase(URL){
return base64;
}
var img = urlToBase('https://unsplash.com/photos/MVx3Y17umaE');
var dd = {
content: [
{
text: 'fjfajhal'
},
{
image: img,
}
]
};
var writeStream = fs.createWriteStream('myPdf.pdf');
var pdfDoc = printer.createPdfKitDocument(dd);
pdfDoc.pipe(writeStream);
pdfDoc.end();
im using PDFmake module from npm
The contents of the remote image can first be fetched with an HTTP request, for example using the ubiquitous request npm module. The image string contents can then be transformed to a buffer and finally converted to a base64 string. To complete the transformation, add the proper data-url prefix, for example, data:image/png,base64, to the beginning of the base64 string.
Here is a rough example for a PNG image:
const request = require('request-promise-native');
let jpgDataUrlPrefix = 'data:image/png;base64,';
let imageUrl = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
request({
url: imageUrl,
method: 'GET',
encoding: null // This is actually important, or the image string will be encoded to the default encoding
})
.then(result => {
let imageBuffer = Buffer.from(result);
let imageBase64 = imageBuffer.toString('base64');
let imageDataUrl = jpgDataUrlPrefix+imageBase64;
console.log(imageDataUrl);
});
I have a meteor application and in this one I get a base64 image. I want to save the image on a Digital Ocean instance, so I would convert it in a png or an other image format and send it to the server to get an url of the image.
But I didn't find a meteor package that does this.
Do you know how I can do that ?
I was running into a similar issue.
run the following:
meteor npm install --save file-api
This will allow the following code on the server for example:
import FileAPI from 'file-api';
const { File } = FileAPI;
const getFile = function(name,image){
const i = image.indexOf('base64,');
const buffer = Buffer.from(image.slice(i + 7), 'base64');
const file = new File({buffer: buffer, name, type: 'image/jpeg'});
return file;
}
Simply call it with any name of file you prefer, and the base64 string as the image parameter.
I hope this helps. I have tested this and it works on the server. I have not tested it on the client but I don't see why it wouldn't work.
I solved my problem using fs.writeFile from File System.
This is my javascript code on client side, I got a base64 image (img) from a plugin and when I click on my save button, I do this :
$("#saveImage").click(function() {
var img = $image.cropper("getDataURL")
preview.setAttribute('src', img);
insertionImage(img);
});
var insertionImage = function(img){
//some things...
Meteor.call('saveTileImage', img);
//some things...
}
And on the server side, I have :
Meteor.methods({
saveTileImage: function(fileData) {
var fs = Npm.require('fs');
var path = process.env.PWD + '/var/uploads/';
base64Data = fileData.replace(/^data:image\/png;base64,/, "");
base64Data += base64Data.replace('+', ' ');
binaryData = new Buffer(base64Data, 'base64').toString('binary');
var imageName = "tileImg_" + currentTileId + ".png";
fs.writeFile(path + imageName, binaryData, "binary", Meteor.bindEnvironment(function (err) {
if (err) {
throw (new Meteor.Error(500, 'Failed to save file.', err));
} else {
insertionTileImage(imageName);
}
}));
}
});
var insertionTileImage = function(fileName){
tiles.update({_id: currentTileId},{$set:{image: "upload/" + fileName}});
}
So, the meteor methods saveTileImage transform the base64 image into a png file and insertionTileImage upload it to the server.
BlobUrl, would it be a better option for you?
Save the images to a server as you like in base64 or whatever, and then when you are viewing the image on a page, generate the blobUrl of it. The url being used only at that time, preventing others from using your url on various websites and not overloading your image server ...
I'm trying to convert some kind of images to jpg and save as a parse file.
Using the parse-image module works for GIF and PNG files, but I need to convert some BMP files too and this module does not work for .bmp files.
Is there anyway for me to do this image conversion on ParseCloud?
This is the code I used for parse-image:
Parse.Cloud.httpRequest({ url: url }).then(function(response) {
// Create an Image from the data.
var image = new Image();
return image.setData(response.buffer);
},function(error) {
console.log("Image not generated " + error.text);
}).then(function(image) {
// Format the image to a JPEG.
return image.setFormat("JPEG");
},function(error) {
console.log("Image set format failed");
})
Tks,
I've got a drag and drop function which takes the file that's been dropped on it and converts it to Base64 data. Before, it was uploading to Imgur, whose API supports Base64 uploads, and now I'm working on moving to Amazon S3.
I've seen examples of people using XMLHTTP requests and CORS to upload data to S3, I'm using Amazon's AWS S3 SDK gem to avoid having to sign policies and other things, as the gem does that for me. So what I've done is send the Base64 data to a local controller metod which uses the gem to upload to S3.
The other posts using Ajax i've seen show that S3 supports raw data uploads, but the gem doesn't seem to, as whenever I view the uploads i get broken images. Am I uploading it incorrectly? Is the data in the wrong format? I've tried the basic Base64, atob Base64, and blob urls, but nothing works so far.
JS:
fr.onload = function(event) {
var Tresult = event.target.result;
var datatype = Tresult.slice(Tresult.search(/\:/)+1,Tresult.search(/\;/));
var blob = atob(Tresult.replace(/^data\:image\/\w+\;base64\,/, ''));
$.ajax({
type:"POST",
data:{
file:blob,
contentType: datatype,
extension:datatype.slice(datatype.search(/\//)+1)
},
url:'../uploads/images',
success:function(msg) {
handleStatus(msg,"success");
},
error:function(errormsg) {
handleStatus(errormsg,"error");
}
});
}
Controller method:
def supload
s3 = AWS::S3.new(:access_key_id => ENV['S3_KEY'],:secret_access_key => ENV['S3_SECRET'])
bucket = s3.buckets['bucket-name']
data = params[:file].to_s
type = params[:contentType].to_s
extension = params[:extension].to_s
name = ('a'..'z').to_a.shuffle[0..7].join + ".#{extension}"
obj = bucket.objects.create(name,data,{content_type:type,acl:"public_read"})
url = obj.public_url().to_s
render text: url
end
Edit:
To be clear, I've tried a couple of different formats, the one displayed above is decoded base64. Regular Base64 looks like this:
var Tresult = event.target.result;
var datatype = Tresult.slice(Tresult.search(/\:/)+1,Tresult.search(/\;/));
var blob = Tresult;
$.ajax({
type:"POST",
data:{
file:blob,
mimeType: datatype,
extension:datatype.slice(datatype.search(/\//)+1)
},
url:'../uploads/images',
success:function(msg) {
handleStatus(msg,"success");
},
error:function(errormsg) {
handleStatus(errormsg,"error");
}
});
and a blob url looks like this:
var blob = URL.createObjectURL(dataURItoBlob(Tresut,datatype));
...
function dataURItoBlob(dataURI, dataType) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: dataType});
}
Am I reading this right that you are:
Using AJAX to send a Base64-encoded file to Rails
Using Rails to upload the file to S3
Viewing the file in S3?
If that's the case, you need to decode the data in step 2 before sending it on to S3. Something like this might work:
require "base64"
def supload
s3 = AWS::S3.new(:access_key_id => ENV['S3_KEY'],:secret_access_key => ENV['S3_SECRET'])
bucket = s3.buckets['bucket-name']
data = Base64.decode64(params[:file].to_s)
type = params[:contentType].to_s
extension = params[:extension].to_s
name = ('a'..'z').to_a.shuffle[0..7].join + ".#{extension}"
obj = bucket.objects.create(name,data,{content_type:type,acl:"public_read"})
url = obj.public_url().to_s
render text: url
end