Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138192

Vuejs: Axios post JSON data and Image data

$
0
0

Currently, I am creating a form with image data and JSON data. I am using 2 post method to post image data and JSON data separately to my nodejs backend. Is it any possible solution that enables me to post once for image and JSON data only by using axios and backend by using nodejs.

The following is my code.

Frontend vue.js

submitAuth() {
  console.log(this.promo.bannerImg)
  const formData = new FormData()
  formData.append('bannerImg', this.promo.bannerImg)
  formData.append('inAppImg', this.promo.inAppImg)
  formData.append('inAppImg', this.promo)

   axios.post(`http://localhost:5000/success`, 
       this.promo
     )
     .then(response => { 
       console.log('Submit Success')
     })
     .catch(e => {
       console.log('Submit Fail')
     })

  axios.post('http://localhost:5000/uploadImg', 
      formData
  ).then(response => {
    console.log('Submit Success')
  }).catch(e => {
    console.log('Submit Fail')
  })
},

},

Backend node.js

app.post("/success", function (request, response) {
  co(function* () {
    var promouid = request.body.uid
    var filename = __dirname + '/public/promo-json/' +  promouid + '.json'
    var promotionJSON = JSON.stringify(request.body)
    fs.writeFile(filename, promotionJSON, 'utf-8', function (err) {
      if (err) throw err;
      console.log(request.body);
    });

    var stream = fs.createReadStream(filename);
    var size = fs.statSync(filename).size;
    var result = yield client.putStream( 
     'promojson/' + promouid + '.json', stream, {contentLength: size});
    console.log(result);
  }).catch(function (err) {
    console.log(err);
  });
});

app.post("/uploadImg", function (req, res) {
  var storage = multer.diskStorage({
        destination: 'public/image', 
        filename: function ( req, file, cb ) {
          // set image name
          console.log()
          cb( null,  'asdasdsad-' + Date.now());
      }
    });
    var upload = multer({
        storage: storage,
    }).any();

    upload(req, res, function(err) {
        if (err) {
            console.log(err);
            return res.end('Error');
        } else {
            console.log(req.body);
            req.files.forEach(function(item) {
                console.log(item);
            });
          res.end('File uploaded');
        }
    });
  });

Viewing all articles
Browse latest Browse all 138192

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>