Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save CSV file from API response using React?

In my application I need to save on my computer a CSV file which comes from an API response. The function which sends POST request is (I am using Redux):

export const postCsv = sensorData => (dispatch, getState) => {

  const token = getState().auth.token;

  // Headers
  const config = {
    headers: {
      'Content-Type': "application/json"
    }
  }

  // If token exists, add to headers config
  if (token) {
    config.headers['Authorization'] = `Token ${token}`
  }

  // Post request to API
  axios.post(`${baseURL}/sensors_data/csv`, sensorData, config)
  .then(res => {
    console.log(res);
    if (res.status === 200) {
      dispatch({
        type: POST_CSV,
        payload: res.data
      })
    }
  })
  .catch(err => {
    console.log(err.response);
  })
} 

and response from API is:

enter image description here

I execute the postCsv function after a button click. As you can see, the response code is 200 and every data has been sent correctly. I just don't know what should I do to download and save the file. Can anyone help?

like image 276
adn98 Avatar asked Oct 24 '25 11:10

adn98


1 Answers

const downloadFile = () => {
      const url = window.URL.createObjectURL(new Blob([response.data])) 
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', "yourfilename.csv")
      document.body.appendChild(link)
      link.click()
      link.remove()
  }
like image 172
HogasAndreiMarius Avatar answered Oct 25 '25 23:10

HogasAndreiMarius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!