简体   繁体   中英

How to convert docx bytes to file Node Js with axios

I am retrieving a docx file from an endpoint a trying to create a file from it. I get a file but its not readable. maybe it's a problem with the format I am recieving the file.

this is how I retrieve the information a create the file:

const response = await axios.post(
  `${process.env.TEMPLATE_HOST}template/data/export`,
  {dataId, clientId},
)

fs.writeFileSync(F.path.public(rowFiltered[0]["Files(s) Name"]), response.data);

and this is part of the data I recieve

                                                             ��_rels/.relsP9��Ruڽ�w
 ��"[Content_Types].xmlP9��R����>~ ��:docProps/core.xmlP9��R��?;��word/theme/theme1.xmlP9��R!��k� ��

docProps/app.xmlP9��R��HR� ���
                              word/fontTable.xmlP9��R�����
 ���word/settings.xmlP9���֏� ��_word/webSettings.xmlP9��R��qK��9 ��Sword/styles.xmlP9��R���XI� ���word/document.xmlP9��R
�wi� ���qword/numbering.xmlP9��R�тsf ���vword/_rels/document.xml.rels9��R�тsf�0xword/_rels/header1.xml.relsP9��R�тsf��yword/_rels/footer1.xml.relsP9��R�тsf��{word/_rels/header2.xml.relsP9��R�тsf�=}word/_rels/footer2.xml.relsP9��R�тsf��~word/_rels/header3.xml.relsP9��R�тsf���word/_rels/footer3.xml.relsP9��R����G$�% ��J�word/media/image1.jpegP9��R��CX�d ��զword/endnotes.xmlP9��Ru�/s�j ����word/footnotes.xmlP9��R���?� ����word/header1.xmlP9��R��
              ]�� ���word/header2.xmlP9��R���?� ���word/header3.xmlP9��R��>�>� ��g�word/footer1.xmlP9��R�k�^�t ���word/footer2.xmlP9��R��>�>� ���word/footer3.xmlPKj�

I've tried to do it with php and it creates the file correctly. the php file size is 47KB and the nodejs is 83KB, but compare part of the information and looks the same.

$fp = fopen('data.docx', 'w');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $templateURl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string),
            )
        );
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
echo strlen($server_output);
fwrite($fp, $server_output);
fclose($fp);

any help is appreciated thanks.

Not sure about this, but this could be because of some option that needs to be set on axios.

Maybe try:

const response = await axios.request(
  responseType: 'stream',
  url: `${process.env.TEMPLATE_HOST}template/data/export`,
  method: 'post',
  data: {dataId, clientId},
)

fs.writeFileSync(F.path.public(rowFiltered[0]["Files(s) Name"]), response.data);

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