1

I need to develop an API which when gets a GET response with an ID it should download a file where it is stored in MongoDB as a Binary buffer.

If I try to print the binary buffer to console.log it works fine but cannot store it to a file or download it. Need help in how easily accomplish this.

I have tried all below but nothing works,

const bufferData = Buffer.from(result.file.buffer,result.file.mimetype);
const s = fs.createWriteStream(`C:/upload/${result.file.originalname}`);
fs.write('c:/uploads/test.txt',file.buffer);
fs.WriteStream('c:/uploads/test.txt',file.buffer);

async handler(ctx,res) {

    console.log("Came to main action handler-- DOWNLOAD");

    const fileId = ctx.params.id;
    console.log("Download step 1: " + fileId);
    try {

        const client = await MongoClient.connect(mongoURL);
        const db = client.db(dbName);
        const collection = db.collection(collectionName);
        const result = await collection.findOne({  _id: new ObjectId(fileId) });
        console.log("Download step 2: " + result.file.originalname);
        const s = fs.createWriteStream(`C:/upload/${result.file.originalname}`);
        console.log("Download step 2: " + result.file.buffer);
        //const originalData = Buffer.from(result.file.buffer, result.file.mimetype);
        const bufferData = Buffer.from(result.file.buffer,result.file.mimetype);
        console.log("Download step 2: " + bufferData);

        client.close();

        

    } catch (error) {
        console.log("error" + error);
    }
    
},

When I hit the API it should download a file with the original data in it. I already have an API which will upload the file to mongoDB in the form of binary buffer. Similarly I need an API to download the file again in its original format.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

0 Answers0