How to display image by getting from node server? - html

I am trying to display an image which was in my index.html. This was kept in <img tag and whenever my server calls index.html file then all the paths of files included in it was also loading by checking for its own services.
All types of files like js, css and html are getting loaded but when it come to img files it was not loading on browser, and no error in console.
Path of an image was correct. I am using fs.readFile() to load files content type which was set to image/png as my image file was .png.
Can anyone make me clear what is going on here?

Thanks to Pankaj Jatav, as in html img tag is base64 decoder, our fs.readFile() encoder must be as base64, as default node has utf-8 as encoder in fs.readFile or writeFile we have to mention encoding type as base64 for images
fs.readFile(filepath, 'base64', (err, file) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'image/png' });
res.write(err);
res.end();
return;
}
res.writeHead(200 , { 'Content-Type': 'image/png' });
res.end(file,'base64');
});
this worked for me.

Related

how to download automatically without print pop up (node js)

I'm making a project where when the page opens, the pdf file is automatically downloaded, I managed to use this:
window.addEventListener('load', () => {
window.print();
})
but I want when windows opens the file is directly downloaded to the directory that I have defined, for example D: / myproject.
is there any way? I don't use pdf library because I make pdf with css myself.
thank you
window will not be accessible on server side code.
If you want to download file in browser, on just open the web page the you can use res.download() as follows:
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/file_name.pdf`;
res.download(file); // Set disposition and send it.
});
As you want to download the file in a specific directory, so you can use the npm module
var download = require('download-file')
app.get('/download', function(req, res){
var url = ${__dirname} + "/upload-folder/file_name.pdf";
var options = {
directory: "path of directory/",
filename: "file_name.pdf"
}
download(url, options, function(err){
if (err) throw err
res.send("Done"); // Set disposition and send it.
})
});
Edit: To convert the html code into the pdf you can use the npm module jspdf

Node JS serving html file with css

I'm practicing pure node js and i've encountred a thing that disturb about http protocole.
I finally served my html page with css after an hour or so of searching and testing my code. Here is my code :
const server = http.createServer((req, res)=>{
if(req.url === "/"){
fs.readFile("index.html", "UTF-8", function(err, data){
res.writeHead(200, {"Content-Type": "text/html"});
res.end(data);
});
}else if(req.url === "/styles.css")){
var cssPath = path.join(__dirname, 'public', req.url);
var fileStream = fs.createReadStream(cssPath, "UTF-8");
res.writeHead(200, {"Content-Type": "text/css"});
fileStream.pipe(res);
};
});
But I didn't understand why it works. Well I've only typed "/" in the browser, I didn't type "/styles.css". And why I don't see "/styles.css" in the URL bar.
I'm sure it's because of how the http protocole is designed but can you help with some explanation of this protocole.
Thank you in advance.
If you had typed /styles.css in the address bar, then you would see the source code the CSS file. For example: this link.
You type /, then the browser asks the server to / and the server responds with an HTML document.
Then the browser renders the HTML document. The HTML document, I assume, includes something like:
<link rel=stylesheet href=/styles.css>
So the browser asks the server for /styles.css and the server responds with a CSS file. The browser then applies that CSS to the HTML document.
It doesn't show /styles.css in the address bar because you are looking at /. The CSS file is just a different resource that is needed to fully render the HTML document that / represents.

how to use xhr.overrideMimeType in Chrome / IE Edge?

I have an issue with sending a file (part of a request in form data format).
The issue seems coming from the fact that only in Chrome for Linux the file (which is CVS file, with .csv extension and basically just text) is sent with mimetype (Content-type in request body) Content-Type: application/octet-stream
So, I am trying to override the mimetype to match the same sent by Chrome on Linux which is text/csv.
However the mimetype is apparently not overriden and still send as octet-stream.
My code:
let xhr = new XMLHttpRequest();
let form = new FormData();
form.append('file', file, file.name); // the file is loaded correctly
form.append('payload', JSON.stringify(data)); // data is just a JSON object
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
// we arrive here both on Debian and Windows 10
}
}
xhr.upload.onerror = function() { .... } // no error
xhr.open('POST', 'http://<my_url>', true);
console.log(file.type);
xhr.overrideMimeType("text/csv");
xhr.send(form);
A couple of notes:
console.log(file.type) actually prints "text-csv" but only in Chrome for Linux (Debian specifically). in the other cases (any other browser or platform) nothing is printed
given the previous point, it seems clear to me for some reason any other browser / platform can't recognize the file type, so the file is sent as octet-stream (general binary file)
xhr.overrideMimeType changes the MIME-type of the response, not the request.
I you want to change the MIME-type of the file, just create a new Blob with an explicit file type:
var blob = new Blob([blob], {type: 'text/csv'});
form.append('file', blob, file.name);
The above changes the MIME-type of the file in the uploaded form to "text/csv", as desired.
PS. If you literally want to change the MIME-type of the whole request (instead of just the file), use xhr.setRequestHeader('Content-Type', 'custom MIME type here');. (This only makes sense if you are sending a non-standard or custom data in the xhr.send method).

Uploading an HTML file via HTML5

I have this weird issue that Im not sure if its normal or not.. Im sure its not
I have a drag and drop area that I can upload any file and it works like a charm.
EXCEPT...
I cant upload any .html or .htm files with it. I can take an html file and rename it to .jpg and it works.
This is my piece of code:
xhr = new XMLHttpRequest()
xhr.open 'PUT', "#{tvr.api.url}/transfer/#{userprofile.UserLink.LinkID}/#{userprofile.UserLink.UserName}/#{channelid}/#{filename}"
xhr.upload.addEventListener "progress", (event, filename) =>
window.Appbusy = true
$($(".file-status-#{uid}").find("span")).text("(#{((event.loaded/event.totalSize)*100).toFixed(2)}%)")
,false
xhr.onreadystatechange = (aEvt) ->
if xhr.readyState is 4
if xhr.status is not 200
$(".notification").remove()
notification("The server returned an error uploading the file. Please try again.", 'error')
It even shows that upload progress then at 100% when it needs to push it the server it just fails with Bad Request. (the server never gets any request)
It works if the HTML file has 0 content! Why I do not know
UPDATE:
After some playing around I see that the request works when setting the Content-Type to text/plain:
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
As soon as I change to text/html it does not work if the file has any content:
xhr.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
Could this be a bug?
I sent this as a possible XML bug
Use jQuery .ajax() instead. Specify type:'PUT' for an upload. For example, using your URL:
$.ajax({
type:"PUT"
url:"#{tvr.api.url}/transfer/#{userprofile.UserLink.LinkID}/#{userprofile.UserLink.UserName}/#{channelid}/#{filename}"
success: function(){
alert('success');
}
});

Loading image binary data returned by Ext.Ajax.request into <img> tag

This is a Sencha Touch + HTML question.
I retrieve image data from server using Ext.Ajax.request.
Ext.Ajax.request({
url: 'http://localhost:3000/someimage.jpg',
method: 'GET',
success: function(res) {
rec.set('imagedata', 'data:image/jpeg;base64{' + res.responseText + '}');
},
failure: function() {
console.log ( 'Failed to GET image data ' + url );
},
scope: this
});
Above res.responseText seems to contain the contents of the jpg file.
At a later point, I pass image data into an tag in html, as follows,
<img src="{imagedata}" style="width:100%;"/>
Result:
Instead of the image, i see garbled text in image box. The garbled text is the content of responseText.
( PS... I am doing this to be able to store the image data locally into a sencha store. )
I would just store the URLs of the images in the store and then create IMG elements on the fly like you do with the src set to the URL instead.
Keep it simple.