首页 > 解决方案 > 不断从流响应中获取 Node js 中损坏或受密码保护的 PDF

问题描述

已经不知道该怎么办了。在这上面花太多时间。

这是我的行动

export const getCardFile = (card_id, filename) => dispatch => {
  fetch(`${config.protocol}://${config.server}:${config.port}/api/v1/get-file-from-card`, {
    method: 'post',
    headers: {
      Authorization: localStorage.getItem('token'),
      'Content-type': 'application/json; charset=UTF-8',
    },
    body: JSON.stringify({ card_id, filename }),
  })
    .then(response => {
      return response.blob();
    })
    .then(blob => {
      FileSaver.saveAs(blob, `file.pdf`);
    })
    .catch(error => console.log('Request failed', error));
};

这是我的控制器

    router.post('/get-file-from-card', checkPermissions(), async (req, res) => {
  const {
    card_id, filename
  } = req.body;


  try {
    const rawFileData = await getFileFromCard(card_id, filename);
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    res.header('content-type', 'application/pdf');
    res.send(rawFileData);
  } catch (err) {
    res.json({
      error: 1,
      message: err.toString()
    });
  }
});

这是控制器的服务助手,它从远程 api 获取流下载数据。

const getFileFromCard = async (card_id, fileName) => {
  return await sendRequest(`card/${card_id}/file`,
    'get', { fileName })
    .then(res => {
      return res.data;
    });
};
const sendRequest = async (api_method, http_method, params = {}) => {
  const url = `${API_URL}/${api_method}`;
  const axios_promise = new Promise(async (resolve, reject) => {
    await axios
      .post(`${API_URL}/auth`, {
        login: API_LOGIN,
        password: API_PASS
      })
      .then(async response => {
        const { token } = response.data;

        const axiosOptions = {
          method: http_method,
          url,
          headers: {
            Authorization: `Bearer ${token}`,
            accept: 'application/json',
            'accept-language': 'en_US',
            'Content-Type': 'application/json'
          }
        };

        if (http_method === 'get') {
          axiosOptions.params = params;
        } else if (['post', 'put'].includes(http_method.toLowerCase())) {
          axiosOptions.data = params;
        }
        await axios(axiosOptions)
          .then(res => {
            resolve(res);
          })
          .catch(err => console.log(err));
      });
  });
  return axios_promise.then(res => res);
};

他们返回二进制数据流以供下载,当我将其发送到我的客户端时,它每次都已损坏或受密码保护。花一整天的时间来修复它。

从 API 返回的数据看起来像

    46 0 obj
<</Names[( ���}��_V�▒Syծ?) 40 0 R( ���}��_V�▒Syծ<) 41 0 R( ���}��_V�▒Syծ=) 42 0 R]>>
endobj
47 0 obj
<</Dests 46 0 R>>
endobj
12 0 obj
<</Perms<</DocMDP 4 0 R>>/Names 47 0 R/Type/Catalog/AcroForm<</Fields[10 0 R]/DR<</XObject<</FRM 8 0 R>>/Font<</Helv 13 0 R/ZaDb 14 0 R>>>>/DA(�.�*▒�0Y��f�ކ�)/SigFlags 3>>/ViewerPreferences<</PrintScaling/None>>/Pages 19 0 R>>
endobj
48 0 obj
<</U (�▒����,�s��濾)/Length 128/V 2/O (^X�P�"�j��LYo��kPRG�X��D��!�)/P -1852/Filter/Standard/R 3>>
endobj
49 0 obj
<</Creator(!�{ \r�`܄777X�3��|3y���x�MY�%)/Producer(�m\(���vrC&I�X\n��|\(s��▒�s�Y� XRvRT�3rF�nx8>2��b���U�o2��m�\f!x)/ModDate(/�:`Z���owQqNI�[a��lb)/CreationDate(/�:`Z���owQqNI�[a��lb)>>
endobj
xref
0 50
0000000000 65535 f 
0000051619 00000 n 
0000054850 00000 n 
0000054877 00000 n 
0000000169 00000 n 
0000054631 00000 n 
0000050771 00000 n 
0000050388 00000 n 
0000051355 00000 n 
0000050520 00000 n 
0000000015 00000 n 
0000054904 00000 n 
0000253936 00000 n 
0000030772 00000 n 
0000030871 00000 n 
0000030948 00000 n 
0000049032 00000 n 
0000049218 00000 n 
0000049740 00000 n 
0000140165 00000 n 
0000133787 00000 n 
0000066323 00000 n 
0000086955 00000 n 
0000065291 00000 n 
0000070244 00000 n 
0000061820 00000 n 
0000121969 00000 n 
0000062793 00000 n 
0000058635 00000 n 
0000055285 00000 n 
0000056889 00000 n 
0000064281 00000 n 
0000186466 00000 n 
0000231141 00000 n 
0000063092 00000 n 
0000253588 00000 n 
0000140244 00000 n 
0000143146 00000 n 
0000140494 00000 n 
0000143396 00000 n 
0000146307 00000 n 
0000146344 00000 n 
0000146381 00000 n 
0000146418 00000 n 
0000186658 00000 n 
0000231342 00000 n 
0000253792 00000 n 
0000253902 00000 n 
0000254180 00000 n 
0000254318 00000 n 
trailer
<</Root 12 0 R/ID [<96e1d0a60b0ddd655eacaf57c27b2870><71919408c34127b9cd081e8a351baf78>]/Encrypt 48 0 R/Info 49 0 R/Size 50>>
startxref
254542
%%EOF

标签: node.jsreactjsrestexpresspdf

解决方案


我不确定这是否会导致问题 res.header('content-type', 'application/pdf');

检查这是否有帮助 res.setHeader("Content-Type", "application/json");


推荐阅读