Shubham Panchal
Shubham Panchal

Reputation: 142

POST File in AXIOS NodeJs

Post file as raw body in AXIOS NodeJS. I tried many ways to achieve this but none of them worked.

What i have tried ?

var file = fs.readFileSync("a.jpg");
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg").toString();
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg",{encoding:"utf8"}).toString();
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg");
file = Buffer.from(file).toString('utf8')
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.createReadStream("a.jpg");
var body = await axios({ method: 'POST', url : "myUrl", data : file });

But none of them worked as i wanted.

Actual working example from JQuery AJAX in Browser

var fileupload = $("#inpFile")[0];
var file = fileupload.files[0];
$.ajax({
    url: "https://hookb.in/b9gqlwbZeaT3DDogQ7Om",
    type: 'POST',
    success: function (response) {
        DisplayMessage(response);
    },
    data: file,
    contentType: false,
    processData: false
});

Upvotes: 0

Views: 9896

Answers (2)

Didier68
Didier68

Reputation: 1325

An example like I tested... In several samples above, there is the same error: don't miss the filename in the FormData, as the 3rd parameter for "form.append()" !

form.append(parameter_name, file_content, file_name);

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 ...',
  },
});

Upvotes: 0

Cody Geisler
Cody Geisler

Reputation: 8617

Have you tried setting the content-type header? Per Talg123 I found that if you set contentType to false in jQuery it might be equivalent to multipart/form-data.

client side:

async function main(){
  try{
    const buffer = new ArrayBuffer(8);
    const data = new FormData();
    const blob = new Blob([buffer],{type : 'multipart/form-data'});
    data.append('data', blob);
    const options = {
      url: "https://hookb.in/b9gqlwbZeaT3DDogQ7Om",
      method: 'POST',
      headers: { 'content-type': 'multipart/form-data' },
      data
    };
    let result = await axios(options);
    console.log(result);
  }catch(e){
    console.error("error",e);
  }
}
main()
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>

server side per https://github.com/axios/axios/issues/1006#issuecomment-584840380

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

// Where buffer is a file
formData.append('file', buffer);

// Added a promise version like seen in earlier comments to get this
const contentLength = await formData.getLength();

await axios(`<ENDPOINT>`, {
    method: 'POST',
    baseURL: <BASE_URL>,
    params: {
        fileName: '<FILE_NAME>.png'
    },
    headers: {
        authorization: `Bearer <TOKEN>`,
        ...formData.getHeaders(),
        'content-length': contentLength
    },
    data: formData
});

js fiddle for image/jpeg

https://jsfiddle.net/bn7yLh61/

Upvotes: 3

Related Questions