简体   繁体   中英

Downloading and sending pdf document in Node through API

I am new to node, I want to download a pdf document from some another url when person hits a post request in the back-end, change the name of file and send the file back to original client where the pdf will be downloaded.
NOTE the file should not be saved in server

first there is controller file which contains following code

try {
      const get_request: any = req.body;
      const result = await printLabels(get_request,res);
      res.contentType("application/pdf");
      res.status(200).send(result);
    } catch (error) {
      const ret_data: errorResponse = await respondError(
        error,"Something Went Wrong.",
      );
      res.status(200).json(ret_data);
    }

Then after this the function printLabels is defined as

export const printLabels = async (request: any,response:any) => {
  try {
    const item_id = request.item_id;
    let doc=await fs.createReadStream(`some url with ${item_id}`);
    doc.pipe(fs.createWriteStream("Invoice_" + item_id + "_Labels.pdf"));
    return doc;
  } catch (error) {
    throw error;
  }
};

Using above code, I am getting error as no such file found. Also, I don't have access of front end so is it possible to test the API with postman for pdf which I am doing or my approach is incorrect?

Next solution working for Express , but I'm not sure if you're using Express-like framework. If that, please specify which framework you're using.

At first, you need to use sendFile instead of send :

try {
      const get_request: any = req.body;
      const result = await printLabels(get_request,res);
      res.contentType("application/pdf");
      res.status(200).sendFile(result);
    } catch (error) {
      const ret_data: errorResponse = await respondError(
        error,"Something Went Wrong.",
      );
      res.status(200).json(ret_data);
    }

Then, you returning readStream , instead of path to file. Notice, you need to use absolute path to do that.

const printLabels = async () => {
  try {
    let doc= await fs.createReadStream(path.join(__dirname, 'test.pdf'));
    doc.pipe(fs.createWriteStream("Invoice_test_Labels.pdf"));
    return path.join(__dirname, 'Invoice_test_Labels.pdf');
  } catch (error) {
    throw error;
  }
};

About PostMan, of course you can see it or save it to file: 截屏

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM