Home > Net >  create downloable file for mobile and desktop
create downloable file for mobile and desktop

Time:12-03

I want to create a vCard in the frontend and to make it downloadable (by clicking a button) in a ReactJs Project. I use a NodeJS module called vcards-js that creates a string with the content of the desired vCard (v3.0). The thing I am struggling with is to make it downloadable (as .vcf file).

here is my code

const {fname,lname,phoneNumber,email,organisation,title}=req.body
  
const mycard=vcard()

mycard.firstName=fname

mycard.lastName=lname

mycard.phoneNumber=phoneNumber

mycard.email=email

mycard.organisation=organisation

mycard.title=title

// enter code here

console.log(mycard.getFormattedString(),"utf-8")

after console.log() i get vcard format data but how to get it downloadable ; pls write the steps

CodePudding user response:

I have not used vcard.js myself but by reading the README at github (https://github.com/enesser/vCards-js#on-the-web) you only redirect the user to the url of the endpoint where you generate the vcard. Something like this:

Nodejs:

var express = require('express');
var router = express.Router();

module.exports = function (app) {
  app.use('/vcard', router);
};

router.get('/', function (req, res, next) {
    var vCardsJS = require('vcards-js');
    var vCard = vCardsJS();

    // Create your vcard here

    res.send(vCard.getFormattedString());
});

Front end:

window.location = "/vcard"

CodePudding user response:

I think your questions is answered here. To translate this answer to your example, it would be something like this:

    var textFile = null,
      makeTextFile = function (text) {
        var data = new Blob([text], {type: 'text/plain'});

        // If we are replacing a previously generated file we need to
        // manually revoke the object URL to avoid memory leaks.
        if (textFile !== null) {
          window.URL.revokeObjectURL(textFile);
        }

        textFile = window.URL.createObjectURL(data);

        // returns a URL you can use as a href
        return textFile;
      };

// -------------

    var create = document.getElementById('create');

    create.addEventListener('click', function () {
    var link = document.createElement('a');
    link.setAttribute('download', 'XXXXX.vcf' /* set your vcf name here*/);
    link.href = makeTextFile(
           mycard.getFormattedString()
    );
    document.body.appendChild(link);

    // wait for the link to be added to the document
    window.requestAnimationFrame(function () {
      var event = new MouseEvent('click');
      link.dispatchEvent(event);
      document.body.removeChild(link);
    });

  }, false);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related