So, I am trying to display an image on my web application. I am getting this image from a Dropbox folder. I want to get a URL I could use to show the image in HTML using the src attribute.
I have written this code:
function downloadFile() {
var Dropbox = require('dropbox').Dropbox;
var ACCESS_TOKEN = "XXXXXXXXXXX"; // Here the access token key
var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
dbx.filesDownload({ path: '/desiredImg.jpg' })
.then(function(response) {
var results = document.getElementById('results');
var img = document.createElement('img');
img.src = window.URL.createObjectURL(response.fileBlob);
console.log(response);
console.log(response.fileBlob);
})
.catch(function(error) {
console.error(error);
});
return false;
}
Result
Error
Can anyone help me figure this out?
The error was from the img.src = window.URL.createObjectURL(response.fileBlob);
It has to be : img.src=window.URL.createObjectURL(response.result.fileBlob);
Related
What I am trying to do : I have a cloud page where the user can upload CSV file. When user clicks on the “upload” button the a function called getBase64() is called (please refer the below code). The getBase64() function will encode the uploaded file and post it to a second cloud page.The second cloud page then takes the posted data.
Note: I am trying to adapt this solution to my need (csv file) by referring to this article partially https://sfmarketing.cloud/2020/02/29/create-a-cloudpages-form-with-an-image-file-upload-option/
What’s the problem : When I try to click the the “upload” button the page is not taking me to the second CloudPage. Please could anyone let me know what I am doing wrong here ?
Here is the code:
CloudPage 1
<input id="file" type="file" accept=".csv">
<br>
<button id="button">Upload</button>
<script runat="client">
document.getElementById("button")
.addEventListener("click", function() {
var files = document.getElementById("file").files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
//prepare data to pass to processing page
var fileEncoded = reader.result;
var base64enc = fileEncoded.split(";base64,")[1];
var fullFileName = document.getElementById("file").files[0].name;
var fileName = fullFileName.split(".")[0];
var assetName = fullFileName.split(".")[1];
fetch("https://cloud.link.example.com/PAGE2", { //provide URL of the processing page
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
base64enc: base64enc,
fileName: fileName,
assetName: assetName
})
})
.then(function(res) {
window.alert("Success!");
})
.catch(function(err) {
window.alert("Error!");
});
};
reader.onerror = function(error) {
console.log('Error: ', error);
};
}
</script>
CloudPage 2
<script runat="server">
var jsonData = Platform.Request.GetPostData();
var obj = Platform.Function.ParseJSON(jsonData);
</script>
I do not see any errors in the code and when I click on the upload button I get a success message but it does not take me to the second page. Please can anyone guide me how to retrieve this posted data in second page as I am not able to get the encoded data in page 2?
Is there any possible ways to get my canvas by blob and send it using telegram api directly? I tried to convert the canvas into a url but telegram still cannot send it.
My system is about sending emergency message. When the alarm was triggered, the live graph will be send to a telegram group to notify the members. But what is troubling me is telegram only can send photo by using url or upload from local.
Below is my code example:
exportTelegramPNG(){
const bot = {
TOKEN:"telegram bot token",
chatID:"telegram bot chatID",
}
const filename = this.state.stationRecord["StationName"]+'_'+this.state.currentDate;
html2canvas(document.getElementById(this.chart2.current.chart.container.id)).then(function (canvas) {
if (canvas) {
canvas.toBlob(function (blob) {
const newImg = document.createElement('img');
const url = URL.createObjectURL(blob);
newImg.onload = () => {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(url);
};
newImg.src = url;
document.body.appendChild(newImg);
fetch(`https://api.telegram.org/bot${bot.TOKEN}/sendPhoto?chat_id=${bot.chatID}&photo=${newImg}`, {
method:"GET"
})
});
}
});
}
Here is the error log in console.
GET https://api.telegram.org/bot${bot.TOKEN}/sendPhoto?chat_id=${bot.chatID}&photo=[object%20HTMLImageElement] 400
Thank you for anyone who gives suggestion and helps.
Telegram api only accept either a url to an image or file/image upload. And you can use any blob data for sending without temporary file.
my code worked as below:
exportTelegramPNG(){
const bot = {
TOKEN: "Telegram bot token",
chatID:"telegram bot chatID",
}
html2canvas(document.getElementById(this.chart2.current.chart.container.id)).then(function (canvas) {
if (canvas) {
canvas.toBlob(function (blob) {
var caption = "Report"+'_'+this.state.currentDate;
var formData = new FormData();
formData.append('photo', blob);
formData.append('caption', caption);
var request = new XMLHttpRequest();
request.open('POST', `https://api.telegram.org/bot${bot.TOKEN}/sendPhoto?chat_id=${bot.chatID}`);
request.send(formData);
});
}
});
}
Now my code will be able to get the data from live chart and send it to telegram group after I click the button.
Thanks to Graficode and Tural who help me and giving suggestion.
Thank you.
I modified the code a bit to make it work for me.
function sendCanvas(obj) {
const bot = {
TOKEN: '5237151266:AAEqn8j4mRDnXxvcApmHJMzaXRsoIhvGKTY',
chatID:'-1001719430367',
}
var canvas = document.getElementById(obj);
if (canvas) {
canvas.toBlob(function (blob) {
var caption = 'Summary Chart';
var formData = new FormData();
formData.append('photo', blob);
formData.append('caption', caption);
var request = new XMLHttpRequest();
request.open('POST', 'https://api.telegram.org/bot' + bot.TOKEN + '/sendPhoto?chat_id=' + bot.chatID);
request.send(formData);
});
}
}
This question is not answering my situation as it is not providing a solution, and I am wondering if now (by 2018) we have a better approach.
So the problem is I would like to call my server which is creating pdf file (not physically) and giving the contents of the file as stream to the http response. Now, with an ajax call to this web service, I want to display the returned data as a pdf file if possible.
function callProducePdf(webServiceUrl, resultAreaId){
var jqxhr = $.ajax({
type:"GET",
url: webServiceUrl
});
jqxhr.done(function(data){
//data contains the pdf in inputStream form
//how can I display the pdf in resultAreaId which is a div?
//if I do something like this it works but this is not what I want
var iframe = $('<iframe height="500px">');
iframe.attr('src', webServiceUrl);
resultAreaId.prepend(iframe, "<br>");
});
jqxhr.fail(function(){
//I have this function defined which is working fine
appendError(resultAreaId);
});
}
server side code:
#GetMapping("/producePdfWithDefault")
public ModelAndView producePdfWithDefault(HttpServletRequest request, HttpServletResponse response) {
Resource resource = new ClassPathResource("/path/a/static/pdf/file.pdf");
InputStream resourceAsStream;
try {
resourceAsStream = resource.getInputStream();
byte[] resourceInBytes = Base64.encodeBase64(IOUtils.toByteArray(resourceAsStream));
response.reset();
response.setContentType("application/pdf");
response.setHeader("content-disposition","inline; filename=documentPreview.pdf");
response.setContentLength(resourceInBytes.length);
OutputStream output = response.getOutputStream();
output.write(resourceInBytes);
output.flush();
output.close();
} catch (IOException e) {
response.setStatus(500);
}
return null;
}
Any help is much appreciated. Thank you..
I would do something like this...
...
jqxhr.done(function(data) {
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "<ANY_FILENAME_WITH_EXTENSION>";
link.click();
}),
...
(untested)
Client will download the file and open it in the default PDF reader.
You can use PDF.js to render your PDF into a canvas element.
The demo below is from their examples
// atob() is used to convert base64 encoded PDF to binary-like data.
// (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
// Base64_encoding_and_decoding.)
var pdfData = atob(
'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({
data: pdfData
});
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
console.log('Page loaded');
var scale = 1.5;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.then(function() {
console.log('Page rendered');
});
});
}, function(reason) {
// PDF loading error
console.error(reason);
});
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<h1>PDF.js 'Hello, base64!' example</h1>
<canvas id="the-canvas"></canvas>
USING PARSE.COM AND THE JAVASCRIPT SDK
With the below code I can get as far as letting the user upload an image from the webpage and storing that as an object in a "file" column in the parse db.
I can store the image details, including the url in the
What i'm unable to do is extract the url back out and display the image on a html page.
I've added the screen shots to show how the data is held in var profilePhoto but i'm then unable to make it show on the page using $("profile_pic").attr('src',jobApplication[0]);
What have I overlooked ? I've searched SO and cannot find an relevant question that helps with this.
RESULTS IN INSPECT ELEMENT
Arguments[1]0: t.Filecallee: function () {length: 1__proto__: Object user_profile.html:408
t.File {_name: "tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg", _source:
t.Promise, _previousSave: t.Promise, _url:
"http://files.parsetfss.com/0fc5cba8-caf7-4c81-aafc…fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg",
name: function…}_name:
"tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg"_previousSave:
t.Promise_source: t.Promise_url:
"http://files.parsetfss.com/0fc5cba8-caf7-4c81-aafc-36390888e497/tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg"proto:
Object
CODE
$(document).ready(function() {
var parseAPPID = "XXX";
var parseJSID = "XXXX";
//Initialize Parse
Parse.initialize(parseAPPID,parseJSID);
$("#fileUploadBtn").on("click", function(e) {
var fileUploadControl = $("#fileUploader")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = file.name;
console.log("here goes nothing...");
var parseFile = new Parse.File(name, file);
parseFile.save().then(function() {
console.log("Woot!");
console.dir(arguments);
var User = Parse.Object.extend("_User")
var jobApplication = Parse.User.current();
jobApplication.set("ProfilePic", parseFile);
jobApplication.save();
var profilePhoto = jobApplication.get("ProfilePic");
console.log(profilePhoto);
$("profile_pic").attr('src',jobApplication[0]);
}, function(error) {
console.log("Error");
console.dir(error);
});
}
});
});
$("profile_pic") returns elements with profile_pic tag name, which obviously is not the thing you need. Don't see your HTML, but if profile_pic is id or class name of your img element, this will work if you type $("#profile_pic") or $(".profile_pic") respectively.
I am using gridfs-stream https://github.com/aheckmann/gridfs-stream & currently i am on displaying image from gridFS.
When reading data it gives me following output. When i append this data to <img src="data:image/jpeg;base64,(data)">, the image doesn't show.
gfs
// create a read stream from gfs...
.createReadStream({ filename: 'error1.png' })
// and pipe it to Express' response
.pipe(res);
Output res :-
Edited :-
I tried this :-
img.src = 'data:image/jpeg;base64,' + btoa(res);
Output rendered is :-
<img src="data:image/jpeg;base64,W29iamVjdCBPYmplY3Rd">
No image shown.
I use file stream demonstrate:
var rstream = fs.createReadStream('test.png');
var bufs = [];
rstream.on('data', function(chunk) {
bufs.push(chunk);
}).on('end', function() { // done
var fbuf = Buffer.concat(bufs);
var base64 = (fbuf.toString('base64'));
res.send('<img src="data:image/jpeg;base64,' + base64 + '">');
});