[Ethereum] IPFS file download

ipfs

I wanted to check that is there any way i can download the IPFS file without running the local demon. I am working on a Dapp where i will be uploading the files over IPFS and sending the link of it to the respective team. I want that team to download the file.

Best Answer

You can add the npm library 'ipfs' in your DApp.

https://www.npmjs.com/package/ipfs

lib/ipfs.js

const IPFS = require('ipfs');
const node = new IPFS();

 /**
 * Function that uploads file onto IPFS
 * @param {JSON} fileDetails Json containing file details that needs to be 
   updated on IPFS
 * @param {function} callback callback function
 */
const uploadFileToIPFS = function(fileDetails, callback) {
    let fileContent = fs.readFileSync(fileDetails.path);
    node.files.add({
        path: fileDetails.originalname,
        content: fileContent
    }, (err, filesAdded) => {
        if (err) {
            return callback(err);
        }
        callback(null, {
            hash: filesAdded[0].hash
        });
    });
};


/**
 * Function that gets the document contents from IPFS, based on the document's hash
 * @param {String} ipfsHash IPFS hash of the document that is being uploaded onto IPFS
 * @param {function} callback callback function
 */
const getFileContentsFromIPFS = function(ipfsHash, callback) {
    node.files.cat(ipfsHash, function(err, data) {
        callback(err, data);
    });
};

routes/ipfs.js

// API that gets the documents from IPFS
router.get('/api/to/get/document/from/ipfs', function(req, res){
    ipfs.getFileContentsFromIPFS(req.query.ipfsHash, function(err, result){
        if (err) {
            res.json({
                status: 'error',
                message: 'Something went wrong while fetching document from IPFS'
            });
        } else {
            //Get the file type
            let isImageOrPdf = fileType(result);
            if (isImageOrPdf.ext == 'pdf') {
                res.writeHead(200,{
                    'Content-type': 'application/pdf'
                });
                res.end(result);
            } else if(isImageOrPdf.ext == 'png' || isImageOrPdf.ext == 'jpg' ){
                res.writeHead(200, {'Content-Type' : 'image/png'});
                res.end(result);
            }
        }
    });
});

And instead of sending the link, send the ipfsHash of the document and whenever they want to download the file, get the ipfsHash and hit the aboove API and that file will be downloaded.

Related Topic