0

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 }); 
2
  • 1
    You need to send the file data as multipart/form-data Commented Jun 25, 2020 at 14:25
  • Yes but i can't change server side code so i have to post file as raw body like that jQuery AJAX example. Commented Jun 25, 2020 at 14:53

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

7 Comments

No sir, it showing "Internal server error" I am using hookb.in for testing this
I swore I had done this with axios, but apparently I used the request module instead. In any case, there are VARIOUS github issues surrounding this on axios. I included an answer that I think might get you where you need to be.
Thank you sir for your reply and valuable time. your code is working without any error. But i need output like this. hookbin.com/E71mgYgN3quDEEaxnoMa/gQlRmn9dj You can see here raw body content
Also you can checkout this jQuery working code jsfiddle.net/tm9n45hg
Your help will really save my days because i am searching for this from last 3 days. but still i didn't get any workaround solution.
|
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.