1

I am working with an api that requires me to send png files as binary data to my backend. In their docs they show how to do this with a curl example ( I have never used curl ) but they dont show how to do this with axios to a node.js server ( despite examples of node.js on everything else).

How would I convert this following example of a curl to post request to a node.js server? I am using axios and react for the front end and Node.js for backend.

Here is the curl example, How would I do this in axios?

Also, How do I convert a .png file to binary data in React before sending post request with axios?

curl -u "<account_sid>:<account_secret>" --data-binary @<filename.png> -H "Content-Type: <content-type of upload>" https://mcs.us1.twilio.com/v1/Services/<chat_service_sid>/Media

KingJoeffrey
  • 303
  • 5
  • 16
  • 1
    Try using the FileReader API to read the png file from disk and then use the `readAsBinaryString()` method to get the data as binary string and just send that directly as request body. This does require your user to click a button to read the file on disk though because you cannot use the FileReader API without user interaction – slebetman Jul 02 '22 at 02:10
  • this is the best solution for my question. I asked it differently https://stackoverflow.com/questions/72876918/how-to-send-a-png-or-jpeg-image-as-binary-to-node-js-server-from-react-app – KingJoeffrey Jul 10 '22 at 08:25

4 Answers4

0

You can convert your cURL requests with this utility: https://kigiri.github.io/fetch/

Yours in particular will look like this, and fetch and axios are nearly identical:

fetch("https://mcs.us1.twilio.com/v1/Services//Media", {
  body: "@<filename.png>",
  headers: {
    Authorization: "Basic PGFjY291bnRfc2lkPjo8YWNjb3VudF9zZWNyZXQ+",
    "Content-Type": "<content-type of upload>"
  },
  method: "POST"
})
Cassidy
  • 3,328
  • 5
  • 39
  • 76
0

You can read this article here.

By MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs/promises');

// Read image from disk as a Buffer
const image = await fs.readFile('./stickers.jpg');

// Create a form and append image with additional fields
const form = new FormData();
form.append('productName', 'Node.js Stickers');
form.append('productDescription', 'Cool collection of Node.js stickers for your laptop.');
form.append('productImage', image, 'stickers.jpg');

// Send form data with axios
const response = await axios.post('https://example.com', form, {
  headers: {
    ...form.getHeaders(),
    Authentication: 'Bearer ...',
  },
});
0

You can convert any curl into httpRequest using https://curlconverter.com/#javascript

and read about curl information from https://everything.curl.dev/http/post

for your curl

curl -u "<account_sid>:<account_secret>" --data-binary @<filename.png> -H "Content-Type: " https://mcs.us1.twilio.com/v1/Services/<chat_service_sid>/Media

`fetch('https://mcs.us1.twilio.com/v1/Services/<chat_service_sid>/Media', {
    method: 'POST',
    headers: {
        'Content-Type': '<content-type of upload>',
        'Authorization': 'Basic ' + btoa('<account_sid>:<account_secret>')
    },
    body: '<filename.png>'
});`
Mr. Dev
  • 71
  • 7
0

You can try to use FileReader to read the given file as binary and send it using fetch/axios.

Second, the curl's -u "<account_sid>:<account_secret>" sends Authorization header. You can simply use btoa(username + ':' + 'password') to achieve that.

Here's an example using fetch and FileReader.

import React, {useState} from 'react';

function FileUploadComponent(){
    const [selectedFile, setSelectedFile] = useState();

    const changeHandler = (event) => {
        setSelectedFile(event.target.files[0]);
    };

  const handleSubmission = () => {
    const reader = new FileReader();
    reader.onload = (event) => {
      const url = 'https://mcs.us1.twilio.com/v1/Services/<chat_service_sid>/Media';
      const headers = {
        Authorization: "Basic " + btoa(username + ":" + password),
        'Content-Type': selectedFile.type
      }
      
      fetch(url, { method: 'POST', body: event.target.result, headers })
        .then((response) => response.json())
        .then((result) => {
          console.log('Success:', result);
        })
        .catch((error) => {
          console.error('Error:', error);
        });
    };

    reader.readAsBinaryString(selectedFile)
  };

  return (
    <div>
      <input type="file" name="file" onChange={changeHandler}/>
      <div>
        <button onClick={handleSubmission}>Submit</button>
      </div>
    </div>
  )
}

Here's some useful links:

https://tr.javascript.info/fetch-basics#submit-an-image https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString

Anton
  • 1,401
  • 8
  • 12