1

how is it possible to download txt with api in next.js

the console.log(ninjas) already shows the correct info

i have tested api postman and works perfect when i use get in postman same info output as console log in code but how do i add feature to download the file so i get a pop up with download

new error

error ReferenceError: triggerDownload is not defined
    at C:\java\node\next\test\.next\server\pages\test2.js:32:147
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

code im using


/////////////////// api scrip audiocodes

export const getStaticProps = async () => {
  var myHeaders = new Headers();
  myHeaders.append("Authorization", "Basic password");
  
  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };
  
  fetch("http://10.0.5.26/api/v1/files/ini", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .then(result => triggerDownload(result, 'board.ini'))
    .catch(error => console.log('error', error));

    return {
      
    }
  }
  ////////////////   start website
  const Backup = () => {
    
return (
    <div>
      <h>Download started</h> 
    </div>
  );
} 
export default Backup;

Output file of log console.log(ninjas)

;**************
;** Ini File **
;**************

;Time & Date: 16/08/2021 09:13:59
;Device Up Time: 48d:21h:38m:41s
;Board: UNIVERGE BX9000
;Board Type: 72
;Serial Number: 9107130
;Software Version: 7.20A.256.721
;DSP Software Version: 5014AE3_R => 723.06
;Board IP Address: 10.0.5.26
;Board Subnet Mask: 255.255.255.0
;Board Default Gateway: 10.0.5.4
;CPU: Cavium Networks Octeon V0.1 @ 500Mhz, total 2 cores, 2 cpus, 1 sockets
;Cores mapping:
;core #0, on cpu #0, on socket #0
;core #1, on cpu #1, on socket #0
;Memory: 512 MB
;Flash size: 64 MB
;Num of DSP Cores: 3
;Num of physical LAN ports: 12
;Client defaults file is being used (file length=1573)
;;;Key features:;Board Type: 72 ;IP Media: VXML ;DATA features: FireWall&VPN ;PSTN Protocols: ISDN IUA=2 CAS ;Security: IPSEC MediaEncryption StrongEncryption EncryptControlProtocol ;Channel Type: RTP DspCh=150 ;HA ;Coders: G723 G729 GSM-FR G727 G722 ;DSP Voice features: IpmDetector ;Control Protocols: MSFT FEU=50 SIP SBC=25 ;Default features:;Coders: G711 G726;

;-----  HW components -----
;
; Slot # : Module type : # of ports
;----------------------------------------------
;      1 : Empty
;      2 : Empty
;      3 : Empty
;----------------------------------------------

;USB Port 1: Empty
;USB Port 2: Empty
;----------------------------------------------


[SYSTEM Params]

SyslogServerIP = 
EnableSyslog = 1
TelnetServerEnable = 2
ENABLEPARAMETERSMONITORING = 1
ActivityListToLog = 'pvc', 'afl', 'dr', 'fb', 'swu', 'naa', 'spc', 'll', 'cli', 'ae'
SyslogServerPort = 0
DayLightSavingTimeStart = '01:01:00:00'
DayLightSavingTimeEnd = '01:01:00:00'
DayLightSavingTimeEnable = 1
HALocalMAC = '00908f8ass'
TR069ACSPASSWORD = ''
TR069CONNECTIONREQUESTPASSWORD = ''
NTPServerIP = ''
SBCWizardFilename = 'templates4.zip'
PM_VEDSPUtil = '1,135,150,15'
clones
  • 21
  • 6
  • Does this answer your question: [how to download file in react js](https://stackoverflow.com/a/50695012/1870780)? – juliomalves Aug 16 '21 at 08:38
  • in that post you suggest file is already on server in file dir. this code is fetch file from api. – clones Aug 16 '21 at 08:47
  • And so is your file, i.e., `http://10.0.5.26/api/v1/files/ini`? Why do you need to fetch it? – juliomalves Aug 16 '21 at 08:49
  • Download (GET) operations use application/octet-stream encoding. Example GET /api/v1/files/ini HTTP/1.1 Host: 10.0.5.26 HTTP/1.1 200 OK Content-Type: application/octet-stream ;************** ;** Ini File ** ;************** ;Board: Mediant SW ;Board Type: 73 ;Serial Number: 101780235059663 ;Slot Number: 1 ;Software Version: 7.20A.200.014 ;DSP Software Version: SOFTDSP => 0.00 ;Board IP Address: 10.4.219.229 ;Board Subnet Mask: 255.255.0.0 ... – clones Aug 16 '21 at 09:46

1 Answers1

1

I am a bit confused about why you are doing response.text(), and later doing ninjas.map, it will map on characters of a string.

assuming you edited it to see console.log or lost something while copying code from multiple files...

if you want to trigger a download dialog with custom content you can do something like this:

function triggerDownload(stringContent = '', filename = 'download.blob') {
  const blob = new Blob([stringContent], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')

  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}
triggerDownload('string, do a JSON.stringify(ninja) if object', 'config.json')

// <a onClick={()=>triggerDownload(ninja.content, `${ninja.id}.ini`)}
// <a onClick={()=>triggerDownload(ninja.content, ninja.id + '.ini')}

there is also mention of js-file-download lib and react-download-link component in a topic mentioned by @juliomalves

so this whole thing might be a duplicate, or all of my assumptions is wrong :)

  • thanks for your help what i want is make button to download ini file i don't want to show the content of the ini in a div – clones Aug 16 '21 at 09:48
  • @clones example above will trigger a download dialog for any content you already have (you were using fetch with custom headers in you example), replace `console.log(result)` with `triggerDownload(result, 'filename.ini')` – Yevhenii Ponomar Aug 16 '21 at 10:11
  • thanks that your helping me out im just a newbie i change the code above but still error error ReferenceError: triggerDownload is not defined at C:\java\node\next\test\.next\server\pages\test2.js:32:147 at runMicrotasks () at processTicksAndRejections (internal/process/task_queues.js:95:5) – clones Aug 16 '21 at 12:47
  • you need to put function declaration first, whole `function triggerDownload(stringContent = '', filename = 'download.blob') { ... }`. and remove `.then(result => console.log(result))` line, because your next `.then` will have result set to undefined(returned value of console.log) or replace with `.then(result => { console.log(result); return result })` – Yevhenii Ponomar Aug 16 '21 at 17:07
  • can you send me the code than i can test it out i have try to change but still errors – clones Aug 16 '21 at 19:58