我们如何使用HTTP请求方法将CSV文件从角度应用程序传递到服务器上运行的节点应用程序 [英] How can we pass a CSV file using HTTP request methods from an angular application to a node application running on a server
问题描述
我已经用angular创建了一个前端应用程序,并使用HTTP服务方法将请求发送到服务器(包含node.js代码).在前端,我创建了一个csv文件,该文件保存在角度组件的同一目录中.我想使用HTTP服务方法将文件发送到服务器(包含node.js代码).我创建了以下代码:
I have created a front-end application in angular, and using HTTP service methods to send request to a server (containing node.js code). At front-end, I have created a csv file which is saved in the same directory of the angular component. I want to send the file to the server (containing node.js code) using HTTP service methods. I have created following code:
在angular.js中开发的客户端(前端)代码:
Code of client side (front-end side), developed in angular.js:
uploadCSVFileOnServer(){
let file = new File([""], "./abc.csv"));
let formData = new FormData();
formData.append("userForm", file);
let userData = {
firstName : "ABC",
lastName : "DEF",
userFormData: formData
}
this.http.post('url', userData)
.subscribe(()=>{
console.log("File uploaded successfully");
})
}
现在http.post()
方法将请求发送到以服务器上运行的node.js编写的方法(getFile()
). node.js代码(服务器端代码)如下:
Now http.post()
methods send request to a method (getFile()
) written in node.js running on a server. The node.js code (server side code) is as follows:
getFile(req, res){
let file = req.body.userData.userFormData ;
// PROBLEM: 'file' is an empty object here
}
我的疑问是,我从客户端发送了一个JavaScript对象,该对象也包含FormData对象(使用键userFormData
).但是,当我尝试在服务器端的getFile()
方法中获取FormData
对象时,我得到了一个也不是FormData
类型的空对象.
My doubt is that, from client side I have sent a javascript object which also contains the FormData object (with key userFormData
). But when I try to fetch the FormData
object in getFile()
method at server side , I get an empty object which is also not of type FormData
.
出什么问题了? FormData.append()
在客户端不起作用吗?
What is the problem? Is FormData.append()
not working at client side?
推荐答案
FormData
对象是一个奇异对象,不能作为JavaScript对象的属性发布.
The FormData
object is an exotic object that can not be POSTed as a property of a JavaScript object.
而是将JSON数据附加到FormData对象:
Instead append JSON data to the FormData object:
uploadCSVFileOnServer(){
let file = new Blob([""], {type: "application/csv"});
let formData = new FormData();
formData.append("csvFile", file, "abc.csv");
let userData = {
firstName : "ABC",
lastName : "DEF",
//userFormData: formData
}
formData.append("userData", JSON.stringify(userData));
this.http.post('url', formData)
.subscribe(()=>{
console.log("FormData uploaded successfully");
})
}
这篇关于我们如何使用HTTP请求方法将CSV文件从角度应用程序传递到服务器上运行的节点应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!