I am getting this error while using POST method with axios and formidable. I am trying to upload a file to an API URL. Here is my code snippet.
var server = http.createServer(function(req, response) {
var filePath = '.';
filePath += req.url;
var mimeType = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword',
'.eot': 'appliaction/vnd.ms-fontobject',
'.ttf': 'aplication/font-sfnt'
};
if (filePath == './') {
filePath += "templates/index.html"
}
if (filePath == './success') {
filePath = "templates/success.html"
}
var postUrl = "https://example.com/345678934/attachments";
const form = formidable({ multiples: true , keepExtensions : true});
const option = {
method:'post',
url: postUrl,
headers : {
'content-type': 'application/json'
}
}
axios.post(option, function(err, fields,files) {
console.log("error from post: ",err)
//response.writeHead(200, {'content-type': 'application/json'});
response.end(JSON.stringify({ fields, files }, null, 2));
console.log("Upload completed");
console.log(files);
}).then(res => {
console.log(`statusCode: ${res.status}`)
console.log(res)
})
.catch(error => {
console.error("error from catch",error)
})
fs.readFile(filePath, function(error, content) {
if (error) {
if (error.code == 'ENOENT') {
response.writeHead(404);
response.end('Page not Found');
} else {
response.writeHead(500);
response.end('Internal error: ' + error.code);
}
} else {
var extname = path.extname(filePath);
response.writeHead(200, {
'Content-Type': mimeType[extname] || 'text/plain'
});
response.end(content, 'utf-8');
}
});
});
server.on('listening', function(err) {
if (err) throw err;
console.log(Date() + ' Server is running...');
});
server.listen(7000);
Here I am expecting to upload all types of file extension and multiple files also can be uploaded to that API URL.
Here it's throwing an exception "error from catch Error: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream"
I had a similar error using FormData on NestJS Application, I don't know if this helps you but to solve my problem i did the following changes:
import * as FormData from 'form-data';
import { Readable } from 'stream';
const form = new FormData();
form.append('file', Readable.from(file.buffer), {
filename: file.originalname,
})
credits to: https://stackoverflow.com/a/70660823/12216924
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With