0
votes

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 ?

1
Yes, it is possible, you can send almost anything by socket. Check this: stackoverflow.com/q/5973825yeya
but its only using nodejs. I want ionic3 as well.Kirron
@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.Parth Mahida

1 Answers

1
votes

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