How can we pass a CSV file using HTTP request methods from an angular application to a node application running on a server

我与影子孤独终老i 提交于 2020-02-07 05:29:05

问题


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:

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");
    })
}

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 
}

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.

What is the problem? Is FormData.append() not working at client side?


回答1:


The FormData object is an exotic object that can not be POSTed as a property of a JavaScript object.

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");
    })
}


来源:https://stackoverflow.com/questions/58806507/how-can-we-pass-a-csv-file-using-http-request-methods-from-an-angular-applicatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!