Prajwal9 Posted August 18, 2016 Share Posted August 18, 2016 (edited) I have an image stored at the server end. Whenever client connects to the server, it sends the image through sockets. The received image I am able to display it on canvas, however I am unable to save the received image in the local disk. I am trying to use fs.writeFile(), but maybe I am not sending the right parameters. How can file handling be done at client end? Any leads to this issue will be helpful. Thank You. [i want to implement this as a basic communication client-server]. To optimize it, is there any way can I achieve same operation in a much faster way? Any working code would also he helpful. Client side programming: <script> var socket = io("http://139.25.100.101:6969"); var ctx = document.getElementById('canvas_win').getContext('2d'); var fs = require('fs'); socket.on("image", function(info) { if (info.image) { var img = new Image(); img.src = 'data:image/jpeg;base64,' + info.buffer; ctx.drawImage(img, 0, 0); var end = new Date().getTime(); document.getElementById("demo").innerHTML = end; fs.writeFile('logo.jpeg', img.src, 'data:image/jpeg;base64,', function(err){ if (err) throw err console.log('File saved.') }) } }); Server side programming: var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var fs = require('fs'); // required for file serving http.listen(6969, function(){ console.log('listening on port 6969'); }); // trying to serve the image file from the server io.on('connection', function(socket){ start = new Date().getTime(); console.log(start); console.log('a user connected'); fs.readFile(__dirname + '/image.jpg', function(err, buf){ socket.emit('image', { image: true, buffer: buf.toString('base64') }); console.log('image file is transmitted'); }); }); Edited August 18, 2016 by Prajwal9 Link to comment Share on other sites More sharing options...
justsomeguy Posted August 18, 2016 Share Posted August 18, 2016 You're confusing client-side and server-side code. I assume your server-side code is using node.js, that only works on the server, not the client. Regular client-side Javascript does not have a require function, for example, that is part of node. There are some libraries that people made to save canvas images as files, to do it with only the client it looks like they set the URL to a data URL with a non-image mime type, although I don't think you can set the filename. It's more common to send the image data to the server and then have the server respond with the correct headers that would cause the browser to save the file. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now