如何使用 angular 上传 csv 并使用 express API 解析数据并发送响应
How to Upload csv using angular and parse data using express API and sent response
我正在尝试发送 csv 文件来表达 api,M 在前端使用 angular
这是示例代码-
app.component.html 文件
<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 文件
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));
}
}
我怀疑问题出在 api,我尝试了多种方法来以正确的方式解析表单数据,但都给出了空结果,最后我得到了数组缓冲区作为输出,但仍然是数组缓冲区无效
快递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)
我用这个 API 得到的输出如下,但不是想要的结果:
{"csv":"45,45,45,45,45,45,87,....","json":[]}
针对这个问题也查了很多SO问题,但是没有找到合适的解决办法,
请让我知道出了什么问题,还需要任何进一步的详细信息
我没有得到确切的问题,但我发现使用 angular 发送原始文件数据有点嘈杂,所以我在将数据发送到 API 之前将其转换为字符串 -
Method Updated in app.component.ts file
fileupload(files: FileList) {
if (files && files.length > 0) {
let file: File = files.item(0);
let fileReader: FileReader = new FileReader();
fileReader.readAsText(file);
fileReader.onload = ev => {
let csvdata = fileReader.result.toString();
let body = {data:csvdata};
return this.http.post('apiurl',body)
.subscribe((data:any)=>console.log(JSON.stringify(data.json)));
};
}
}
现在我正在获取字符串格式的数据,所以现在很容易将字符串转换为 json
API method updated-
app.post('/reportfile', (req, res)=>{
let csvDataBuffer = JSON.stringify(req.body);
let csvData = JSON.parse(csvDataBuffer).data;
let csvDataString = csvData.toString("utf8");
return csvtojson()
.fromString(csvDataString)
.then(json => {
return res.status(201).json({csv:csvDataString, json:json})
})
})
通过这种方式,我能够使用 API 将 csv 文件转换为 json 数据,
同样的 csv 文件也可以在客户端转换为 json,但要求是在 API
我正在尝试发送 csv 文件来表达 api,M 在前端使用 angular 这是示例代码- app.component.html 文件
<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 文件
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));
}
}
我怀疑问题出在 api,我尝试了多种方法来以正确的方式解析表单数据,但都给出了空结果,最后我得到了数组缓冲区作为输出,但仍然是数组缓冲区无效
快递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)
我用这个 API 得到的输出如下,但不是想要的结果:
{"csv":"45,45,45,45,45,45,87,....","json":[]}
针对这个问题也查了很多SO问题,但是没有找到合适的解决办法, 请让我知道出了什么问题,还需要任何进一步的详细信息
我没有得到确切的问题,但我发现使用 angular 发送原始文件数据有点嘈杂,所以我在将数据发送到 API 之前将其转换为字符串 -
Method Updated in app.component.ts file
fileupload(files: FileList) {
if (files && files.length > 0) {
let file: File = files.item(0);
let fileReader: FileReader = new FileReader();
fileReader.readAsText(file);
fileReader.onload = ev => {
let csvdata = fileReader.result.toString();
let body = {data:csvdata};
return this.http.post('apiurl',body)
.subscribe((data:any)=>console.log(JSON.stringify(data.json)));
};
}
}
现在我正在获取字符串格式的数据,所以现在很容易将字符串转换为 json
API method updated-
app.post('/reportfile', (req, res)=>{
let csvDataBuffer = JSON.stringify(req.body);
let csvData = JSON.parse(csvDataBuffer).data;
let csvDataString = csvData.toString("utf8");
return csvtojson()
.fromString(csvDataString)
.then(json => {
return res.status(201).json({csv:csvDataString, json:json})
})
})
通过这种方式,我能够使用 API 将 csv 文件转换为 json 数据, 同样的 csv 文件也可以在客户端转换为 json,但要求是在 API