Display Image in GridFS - javascript

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 + '">');
});

Related

Display image from Dropbox to a webpage

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

How can I export data from a csv file or excel file to a javascript object?

I would like to know if there is a way to export data from a CSV file to a javascript object and when someone edits the CSV file it automatically changes in the javascript file. Thank you so much.
The following steps are implemented in the below code snippet.Customize this as required.
Select input CSV file. (The code snippet is tested for UTF-8 encoded CSV file)
Read the CSV file data
Parse the CSV file data and contruct the JSON object
Manipulate or modify the JSON object if required.
Export the JSON object as CSV
var CsvRows;
var headers;
// This event will be triggered when file is selected
// Note: This code is tested for UTF-8 encoded CSV file
function handleChange(evt) {
var reader = new FileReader();
reader.onload = function() {
//reader.result gives the file content
document.getElementById('out').innerHTML = reader.result;
//parse the result into javascript object
var lines = reader.result.split('\r\n');
headers = lines[0].split(',');
lines.shift();
CsvRows = lines.map((item) => {
var values = item.split(',');
var row = {};
headers.map((h, i) => {
row[h] = values[i];
});
return row;
});
console.log(CsvRows);
document.getElementById('result').style.display = 'block'
};
//read the selected file
reader.readAsBinaryString(evt.files[0]);
};
//export the javscript object as csv
function exportCSV() {
//contruct the csv ad data url
let csvContent = "data:text/csv;charset=utf-8," +
headers.join(",") + "\r\n";
//contruct the data in csv format
var data = CsvRows.map(e => {
var line = '';
headers.map((h) => {
line += e[h] + ',';
});
return line.substr(0, line.length - 1);
}).join("\r\n")
csvContent += data;
//contruct an anchor tag
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
//provide the export file name
link.setAttribute("download", "mydata.csv");
document.body.appendChild(link); // Required for FF
//trigger download of CSV
link.click();
link.remove();
}
<input type="file" onchange="handleChange(this)" accept=".csv" />
<div id="result" style="display:none;">
<div id="out"></div>
<div>See console for Javascript Object.</div>
<div>Export the imported file <button onclick="exportCSV()">Export</button></div>
</div>
The above code snippet only works for CSV files. Custom implementation has to be made for Excel files.

display pdf with the returned data - not iframe - by using ajax call - JQuery

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>

How to send a base64 image to node js server

I know how to retrieve the base64 image from the canvas using javascript on the HTML page:
var url = canvas.toDataURL("image/png");
url.replace(/^data:image\/(png|jpg);base64,/, "");
now i want to send this information to the server and create the image.
i want to do something like:
router.post('/createImage', function (req, res) {
var base64image = //i need to get the base64 image here
var picPath = path.normalize('./public/images/users/pic.png');
fs.writeFile(picPath, url, 'base64', function(err) {
console.log(err);
});
});
how can i do that?

How to save an Image in Parse.com via JavaScript?

I wanna add new Object that containing an Image in one of its columns , but it dose not save My Pic , Is there any mistake in my code ? specially part of saving Image !!
My JavaScript where the problem appeared:
It never upload my pic in parse !!
<script type="text/javascript">
Parse.initialize("key", "key");
var products = Parse.Object.extend("products");
var fileUploadControl = $("#profilePhotoFileUpload")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
}
parseFile.save().then(function() {
//The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
</script>
Here I added html line to upload file:
<input type="file" id="profilePhotoFileUpload">
I got the answer I am sharing it with you maybe someone get benefit
The THML line to upload file is:
<input type="file" id="pic">
The code in <script> to get and save image in parse is :
var fileUploadControl = $("#pic")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
//put this inside if {
parseFile.save().then(function() {
// The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
// Be sure of ur parameters name
// prod is extend of my class in parse from this: var prod = new products();
prod.set("picture", parseFile);
prod.save();
}
Check the documentation here (at the end of that section, just before the one about retrieving files). Basically the issue is that like any other Parse object you need to save it first, then after the save is complete you can use it.
Create the file, save it, and in the save success handler you can then save the object with the reference to the file.
UPDATE: here's how your code above could be fixed:
Parse.initialize("key", "key");
var products = Parse.Object.extend("products");
var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
var file = new Parse.File("mypic.png", { base64: base64 });
file.save({
success: function(file) {
alert('File saved, now saving product with file reference...');
var prod = new products();
// to fill the columns
prod.set("productID", 1337);
prod.set("price", 10);
//I guess it need some fixing here
prod.set("picture", file);
prod.set("productName", "shampoo");
prod.set("productDescribe", "200 ml");
prod.save(null, {
success: function(prod) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + prod.id);
},
error: function(error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
},
error: function(error) {
alert('Failed to save file: ' + error.description);
}
});

Categories

Resources