I m trying to send csv file to express api, M using angular at front-end Here is the sample code- app.component.html file
<div>
<h1 style="text-align:center">CSV File Upload</h1>
<form enctype="multipart/form-data">
<input type="file" name="csvreport" id="csvreport" (change)="fileupload($event.target.files)">
</form>
</div>
app.component.ts file
import { Component } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
constructor(private http: HttpClient) {}
fileupload(files: FileList) {
let file: File = files.item(0);
let formData = new FormData();
formData.append("file", file, file.name);
this.http.post('http://localhost:5000/chartreportx/us-central1/chartreportapi/reportfile', formData)
.subscribe(data=>{console.log(JSON.stringify(data))}, err=>{console.log(err)});
console.log(JSON.stringify(file.name));
}
}
I suspect that the issue is with api, I have tried multiple methods to get the formdata parse in the right way but all gives null result, Finally I got array buffer as output, but still array buffer is not valid
Express API:
import * as functions from 'firebase-functions';
import * as express from "express";
import * as bodyParser from "body-parser";
import * as csvtojson from 'csvtojson';
import * as file_upload from 'express-fileupload';
const app = express();
app.use(file_upload())
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, DELETE, OPTIONS"
);
next();
});
app.get('/',(req, res) =>{
res.status(200).json({chartreportapi:'works'});
})
app.post('/reportfile', (req, res)=>{
let csvDataBuffer = JSON.stringify(req.body);
let csvData = JSON.parse(csvDataBuffer).data;
let csvDataString = csvData.toString('utf8')
console.log(csvData.toString('utf8'));
return csvtojson().fromString(csvDataString).then(json => {return res.status(201).json({csv:csvDataString, json:json})})
})
exports.chartreportapi = functions.https.onRequest(app)
Output which i m getting with this API is as follows, but is not the desired result:
{"csv":"45,45,45,45,45,45,87,....","json":[]}
Have also checked many SO questions for this issue, but not found any proper solution, Please let me know what is going wrong, also any further detail is required on this