Return url from attachment PouchDB - javascript

I am trying to create a Webpage with CouchDB and PouchDB. At the beginning I created a CouchDB Database ('image'). In this Database is one document with several attachments, all images (.png). I was able to sync the CouchDB database with PouchDB. Now I want to use the attachments stored in PouchDB.
I used the db.get statement to get the attachments.
db.get('image', {attachments: true}).then(function (doc) {
console.log(doc);
});
Now I want to get the different images because I need them as src at a different place. At the moment I am using:
db.getAttachment('image', 'image1.png').then(function (blob) {
var url = URL.createObjectURL(blob);
console.log('URL image1 created');
}).catch(function (err) {
console.log('URL image1 not created');
console.log(err);
});
The problem is that I don't know how to access the created url. I guess I have to use return and work with a global variable. But I don't know how to do this in this context.
I used the following guide but, as I said, I want to use the url somewhere else in the code.

Part of the solution
The problem seems to be that the url is generated after the img tag tries to access the url. Which means that even if you are working with global variables you get an error. Therefore I changed the order.
Now the src is updated after the url was generated. The problem is still that it is kind of complicated and not really useful in case you are working with several attachments. I still would prefer to get the url for further use.
<body>
<img id ="test" alt="Image from DB" style="width:304px;height:228px;">
<script>
var url = " ";
var imageFW = db.getAttachment('image', 'image1.png');
imageFW.then(function (blob) {
url = URL.createObjectURL(blob);
document.getElementById("test").src = url;
}).catch(function (err) {
console.log(err);
});
</script>
Update:
At the end I solved the problem working with promises

Related

How to convert Base64 string to PNG (currently using Jimp)?

I'm currently creating a real-time chat application. This is a web application that uses node.js for the backend and uses socket.io to connect back and forth.
Currently, I'm working on creating user profiles with profile pictures. These profile pictures will be stored in a folder called images/profiles/. The file will be named by the user's id. For example: user with the id 1 will have their profile pictures stored in images/profiles/1.png. Very self-explanatory.
When the user submits the form to change their profile picture, the browser JavaScript will get the image, and send it to the server:
form.addEventListener('submit', handleForm)
function handleForm(event) {
event.preventDefault(); // stop page from reloading
let profilePicture; // set variable for profile picture
let profilePictureInput = document.getElementById('profilePictureInput'); // get image input
const files = profilePictureInput.files[0]; // get input's files
if (files) {
const fileReader = new FileReader(); // initialize file reader
fileReader.readAsDataURL(files);
fileReader.onload = function () {
profilePicture = this.result; // put result into variable
socket.emit("request-name", {
profilePicture: profilePicture,
id: userID,
}); // send result, along with user id, to server
}
}
I've commented most of the code so it's easy to follow. The server then gets this information. With this information, the server is supposed to convert the sent image to a png format (I can do whatever format, but it has to be the same format for all images). I am currently using the jimp library to do this task, but it doesn't seem to work.
const jimp = require('jimp'); // initialize Jimp
socket.on('request-name', (data) => { // when request has been received
// read the buffer from image (I'm not 100% sure what Buffer.from() does, but I saw this online)
jimp.read(Buffer.from(data.profilePicture), function (error, image) {
if (error) throw error; // throw error if there is one
image.write(`images/profiles/${data.id}.png`); // write image to designated place
}
});
The error I get:
Error: Could not find MIME for Buffer <null>
I've scoured the internet for answers but was unable to find any. I am available to use another library if this helps. I can also change the file format (.png to .jpg or .jpeg, if needed; it just needs to be consistent with all files). The only things I cannot change are the use of JavaScript/Node.js and socket.io to send the information to the server.
Thank you in advance. Any and all help is appreciated.
If you're just getting the data URI as a string, then you can construct a buffer with it and then use the built in fs to write the file. Make sure the relative path is accurate.
socket.on('request-name', data => {
const imgBuffer = Buffer.from(data.profilePicture, 'base64');
fs.writeFile(`images/profiles/${data.id}.png`, imgBuffer);
}

Chrome blocking PDF views on web redirection to new tab via Top-Frame Navigations

As per the Chrome version >=60 the PDF view functionality by any top-frame navigations options like
<A HREF=”data:…”>
window.open(“data:…”)
window.location = “data:…”
has been blocked by Google for which the discussion can be found at Google Groups. Now the problem is how to display the PDF on web without explicitly or forcibly making PDF to download. My old code looked as below via window.open to view the PDF data
dataFactory.getPDFData(id, authToken)
.then(function(res) {
window.open("data:application/pdf," + escape(res.data));
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
In above I extract the PDF data from server and display it. But since window.open is blocked by Chrome and as suggested by one of the expert over here to use <iframe> to open the PDF data and I tried but it's not working. It always says Failed to Load PDF Data as below
The updated JS code for the <iframe> looks as below:
dataFactory.getPDFData(id, authToken)
.then(function(res) {
$scope.pdfData = res.data;
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
And the HTML looks as below:
<iframe src="data:application/pdf;base64,pdfData" height="100%" width="100%"></iframe>
How can I proceed and bring back the original PDF view functionality? I searched over other stack questions but out of luck on how to resolve this. May be I did something wrong or missed something with the iframe code but it's not working out.
After unable to find the desired result I came up with below approach to resolve the issue.
Instead of opening the PDF on new page what I did is as soon as user clicks on the Print button PDF file gets downloaded automatically. Below is the source for same.
//File Name
var fileName = "Some File Name Here";
var binaryData = [];
binaryData.push(serverResponse.data); //Normal pdf binary data won't work so needs to push under an array
//To convert the PDF binary data to file so that it gets downloaded
var file = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
var fileURL = document.createElement("fileURL");
fileURL.href = file;
fileURL.download = serverResponse.name || fileName;
document.body.appendChild(fileURL);
fileURL.click();
//To remove the inserted element
window.onfocus = function () {
document.body.removeChild(fileURL)
}
In your old code :
"data:application/pdf," + escape(res.data)
In the new :
your iframe src is like "data:application/pdf;base64,pdfData"
Try to remove base64 from the src, it seems to be already present in the value of 'pdfdata'.

Display images from dropbox with javascript api

I'm trying to create a page that could show all pictures in a dropbox folder through the Javascript API.
I was able to set up my dropbox app properly, and I am able to get a list of files.
I'm stuck at the part to get a URL I could actually use to show the picture in HTML. I tried the following code, to try and get the URL for 1 image for the time being:
dbx.filesListFolder({path: ""})
.then(function(response) {
console.log(response);
// ↑ this works!
dbx.filesGetThumbnail({path: response.entries[0].path_display, format: "jpeg", size: "w64h64"})
.then(function(result) {
window.data = result;
console.log(result);
})
// closures and rest of code...
Inspecting the window.data or the console.log(result), I cannot seem to find any URL I could use in my HTML.
Any pointers to head me in the right direction? I'm still new to the Dropbox Javascript API.
Kudos to Greg
The filesGetThumbnail method doesn't itself return a URL for the thumbnail data. It returns the raw thumbnail data directly. If you want a URL to display locally in the browser, you may want to something like this:
dbx.filesGetThumbnail({"path": "/test.jpg"})
.then(function(response) {
var img = document.createElement('img');
img.src=window.URL.createObjectURL(response.fileBlob);
document.body.appendChild(img);
})
.catch(function(error) {
console.log("got error:");
console.log(error);
});
BTW, you can find all of the API v2 JavaScript SDK methods documented here.
For others has the same issue :)
Now Dropbox JS Api returns base64 image data instead, so you need to do something like this:
var img = document.createElement('img');
img.src = "data:image/jpg;base64, " + <data returned>;
data:image/jpg depends on which image type you requested

Doing something after a file has been downloaded

I'm kinda new to programming in general. My problem is that I want to download a file and after that do something.
Danbooru.search(tag, function (err, data) { //search for a random image with the given tag
data.random() //selects a random image with the given tag
.getLarge() //get's a link to the image
.pipe(require('fs').createWriteStream('random.jpg')); //downloads the image
});
now I want to do a console.log after the file has been downloaded. I don't want to work with setTimeout since the files will take a diffrent time to download.
Thanks for the help.
See if this works for you. Just saving the request to a variable and checking for the finish event on it.
Danbooru.search(tag, function (err, data) {
var stream = data.random()
.getLarge()
.pipe(require('fs').createWriteStream('random.jpg'));
stream.on('finish', function() { console.log('file downloaded'); });
});

Take screenshot specifies element in Javascript

I want to save 1 image in my local website.
I'll research all internet, I find almost is C# and Java code but I can't convert it to Javascrip.
Almost example using Point, IO library is not available in javascript.
I also search code in nodejs in Stackoverflow.
I've was test but it not working for me.
Present,
My code can Takescreenshot all webpage but I want it capture image with id.
Here is code:
driver.findElement(webdriver.By.xpath('//img[#id="c_pages_Image"]'))
.then(function(){
driver.takeScreenshot("c:\\selenium_local_map\\out1.png");
});
driver.takeScreenshot().then(function(data){
var base64Data = data.replace(/^data:image\/png;base64,/,"")
fs.writeFile("out.png", base64Data, 'base64', function(err) {
if(err) console.log(err);
});
});
let imageElement = await driver.wait(until.elementLocated(By.xpath('//img')), 5000) // returns image element
let screenshot = await imageElement.takeScreenshot(false) // takes screenshot of image element
fs.writeFileSync('\path\to\target\file', screenshot, 'base64')

Categories

Resources