Home > Enterprise >  Create csv and post as multipart/form-data in JavaScript
Create csv and post as multipart/form-data in JavaScript

Time:06-28

How can I create an equivalent code in JavaScript?

Given ['col1', 'col2'] and ['val1', 'val2'] OR 'col1,col2\r\nval1,val2\r\n'

I want to be able to create a csv object without reading/writing to disk and then POST it.

Python:

from io import StringIO
import csv
import requests

f = StringIO()
w = csv.writer(f)
w.writerow(['col1', 'col2'])
w.writerow(['val1', 'val2'])
input_byte = f.getvalue().encode('UTF-8')

headers = {'Content-Type':"multipart/form-data"}
endpoint = "http://localhost:8085/predict"
files = {'file': ('input.csv', input_byte)}
response = requests.post(endpoint, files=files)

Here is my code in JavaScript so far:

let data = [['col1', 'col2'],
            ['val1', 'val2']];
// convert to csv format
let csvContent = data.map(e => e.join(",")).join("\r\n")   "\r\n";
// I believe FormData object is required to send multipart/form-data
// I do not think I am passing my csv data correctly
let body = new FormData();
let buff = Buffer.from(csvContent, "utf-8");
body.append("file", buff, {filename : 'input.csv'});

let response = await fetch("http://localhost:8085/predict",
               {
                  method: 'POST',
                  body: body,
                  headers: {'Content-Type':"multipart/form-data"}
               });

EDIT:

I was able to send a csv file but had to write it to a disk first. Is it possible to avoid it?

let data = [['col1', 'col2'],
            ['val1', 'val2']];
// convert to csv format
let csvContent = data.map(e => e.join(",")).join("\r\n")   "\r\n";

// save a csv file
let path = './files/'   Date.now()   '.csv';
fs.writeFile(path, csvContent, (err) => {
  if (err) {
    console.error(err);
  }
});

let body = new FormData();
// this works :)
// but how can I create a csv buffer without writing to a disk?
body.append("file", fs.createReadStream(path), {filename : 'input.csv'});
let response = await fetch("http://localhost:8085/predict",
               {
                  method: 'POST',
                  body: body,
               });

CodePudding user response:

I was able to solve my question with the following script:

const FormData = require('form-data');
const Readable = require('stream').Readable;
const fetch = require("node-fetch");

let data = [['col1', 'col2'],
            ['val1', 'val2']];
// convert to csv format
let csvContent = data.map(e => e.join(",")).join("\r\n")   "\r\n";
const stream = Readable.from(csvContent);

let body = new FormData();
body.append("file", stream, {filename : 'input.csv'});
let response = await fetch("http://localhost:8085/predict",
               {
                  method: 'POST',
                  body: body,
               });

CodePudding user response:

You can try like this:

let data = [['col1', 'col2'],
            ['val1', 'val2']];
// convert to csv format
let csvContent = data.map(e => e.map(val => JSON.stringify(val)).join(",")).join("\r\n")   "\r\n";

let body = new FormData();
body.append("file", new File(csvContent, {type: "text/csv"}), 'input.csv');

let response = await fetch("http://localhost:8085/predict",
{
  method: 'POST',
  body: body,
});
  • Related