0

I am using Ionic v3 and and for backend used Nodejs.

var storage = multer.diskStorage({ destination: function(req, file, callback) { callback(null, './uploads') }, filename: function(req, file, callback) { console.log(file) callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)) } }); 

var upload = multer({storage: storage});

To call this method we require req ,res through API call like below,

upload(req, res, function(err) { res.end('File is uploaded') }); 

My question that is it possible to call this upload function without API call(req,res) ? If yes how can we do ?

What i want to do is, I am developing chat application using ionic2 and nodejs where i can share image. That image should be upload to server side. How can I do for socket programming ?

4
  • Possible duplicate of Can I upload a file to server by socket.io in node.js? Commented Feb 15, 2018 at 9:28
  • Yes, it is possible, you can send almost anything by socket. Check this: stackoverflow.com/q/5973825 Commented Feb 15, 2018 at 9:29
  • but its only using nodejs. I want ionic3 as well. Commented Feb 15, 2018 at 9:47
  • @KiranDevkar you need to submit form or send a http request to nodeJS server and get files object in request. You may also have to use multiparty npm plugin to parse multipart/form-data. Commented Feb 15, 2018 at 10:20

1 Answer 1

1

If you want to upload image using base64 then you can use following code

socket.on('Upload_Image_base64', function(data) { var fs = require('fs'); var img = data.image64; var imgname = new Date().getTime().toString(); imgname = data.userid + imgname + '.png'; var data = img.replace(/^data:image\/\w+;base64,/, ""); var buf = new Buffer(data, 'base64'); fs.writeFile(__dirname + "/uploads/" +imgname, buf); }); 

// here data.image64 and data.userid --> is the parameter which we pass during socket event request. For multi part - this may help you.

socket.on('Upload_Image', function(data) { var app = require('express')(); var multer = require('multer') var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/') }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now()) } }) var upload = multer({ storage: storage }).single(data.file); console.log(data.file); app.post('/', function (req, res) { upload(req,res,function(req,res) { if(err) { console.log("error uploading file"); } else { console.log("uploaded"); } }); }); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.