Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post binary using Axios?

I'm trying to make a post request to a server that accepts a binary file upload with Authentication token in header

I was able to achieve this using XMLHttpRequest(), but are there ways to use axios to achieve the same thing?

I've tried

axios.post(url, File, {
    headers: {
        'Content-Type': File.type,
        'Authentication' : faketoken
    }
})

where File is an instance of Html5 File interface, this doesn't work, for some reason when I exam the request header in chrome, the content-type is application/x-www-form-urlencoded

thanks in advance

Regards

like image 839
ChenL Avatar asked May 03 '18 05:05

ChenL


People also ask

How do I upload files using Axios?

– First we import Axios and Bootstrap, then we write some HTML code for the UI. For 2 onClick events, there are 2 functions that use Axios for working with Rest API Server: uploadFile() : POST form data with a callback for tracking upload progress. getFiles() : GET list of Files' information.

How do I post Axios?

A POST request can be made using Axios to “post” data to an endpoint. This endpoint may then use this POST request to perform a certain task or trigger an event. The HTTP post request is performed by calling axios.

Can I use Axios on node?

Introduction. Axios is a very popular JavaScript framework used to perform network requests. Axios works both on the browser and Node.


1 Answers

You can upload a file to an API that accepts binary file upload like this:

const file = fs.readFileSync("/path/to/file");
await axios({
    method: 'post',
    url: uploadUrl, //API url
    data: file, // Buffer
    maxContentLength: Infinity,
    maxBodyLength: Infinity
});
like image 179
Murat Colyaran Avatar answered Oct 23 '22 06:10

Murat Colyaran