how to import CSV file in angular 4 and stored data in Database?












1














i want to import CSV in angular 4, and store data in my database.



<input type="file" name="importCSV">
<button type="submit" class="btn btn-primary">Submit</button>


while i click on the Submit button i want to store data in my Table.










share|improve this question






















  • Have a look at this answer
    – Aravind
    Dec 6 '17 at 12:00










  • i didn't get data of CSV file? @Szarik
    – Chaudhary
    Dec 6 '17 at 12:49










  • @Chaudhary had you get the solution of your answer.
    – Vishwa Pratap
    Nov 12 '18 at 16:22










  • @VishwaPratap i post my answer, you can change the function as per your requirement.
    – Chaudhary
    Nov 13 '18 at 6:28










  • @Chaudhary thanks for your response
    – Vishwa Pratap
    Nov 13 '18 at 10:30
















1














i want to import CSV in angular 4, and store data in my database.



<input type="file" name="importCSV">
<button type="submit" class="btn btn-primary">Submit</button>


while i click on the Submit button i want to store data in my Table.










share|improve this question






















  • Have a look at this answer
    – Aravind
    Dec 6 '17 at 12:00










  • i didn't get data of CSV file? @Szarik
    – Chaudhary
    Dec 6 '17 at 12:49










  • @Chaudhary had you get the solution of your answer.
    – Vishwa Pratap
    Nov 12 '18 at 16:22










  • @VishwaPratap i post my answer, you can change the function as per your requirement.
    – Chaudhary
    Nov 13 '18 at 6:28










  • @Chaudhary thanks for your response
    – Vishwa Pratap
    Nov 13 '18 at 10:30














1












1








1







i want to import CSV in angular 4, and store data in my database.



<input type="file" name="importCSV">
<button type="submit" class="btn btn-primary">Submit</button>


while i click on the Submit button i want to store data in my Table.










share|improve this question













i want to import CSV in angular 4, and store data in my database.



<input type="file" name="importCSV">
<button type="submit" class="btn btn-primary">Submit</button>


while i click on the Submit button i want to store data in my Table.







node.js angular angular2-forms






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 6 '17 at 11:58









Chaudhary

829628




829628












  • Have a look at this answer
    – Aravind
    Dec 6 '17 at 12:00










  • i didn't get data of CSV file? @Szarik
    – Chaudhary
    Dec 6 '17 at 12:49










  • @Chaudhary had you get the solution of your answer.
    – Vishwa Pratap
    Nov 12 '18 at 16:22










  • @VishwaPratap i post my answer, you can change the function as per your requirement.
    – Chaudhary
    Nov 13 '18 at 6:28










  • @Chaudhary thanks for your response
    – Vishwa Pratap
    Nov 13 '18 at 10:30


















  • Have a look at this answer
    – Aravind
    Dec 6 '17 at 12:00










  • i didn't get data of CSV file? @Szarik
    – Chaudhary
    Dec 6 '17 at 12:49










  • @Chaudhary had you get the solution of your answer.
    – Vishwa Pratap
    Nov 12 '18 at 16:22










  • @VishwaPratap i post my answer, you can change the function as per your requirement.
    – Chaudhary
    Nov 13 '18 at 6:28










  • @Chaudhary thanks for your response
    – Vishwa Pratap
    Nov 13 '18 at 10:30
















Have a look at this answer
– Aravind
Dec 6 '17 at 12:00




Have a look at this answer
– Aravind
Dec 6 '17 at 12:00












i didn't get data of CSV file? @Szarik
– Chaudhary
Dec 6 '17 at 12:49




i didn't get data of CSV file? @Szarik
– Chaudhary
Dec 6 '17 at 12:49












@Chaudhary had you get the solution of your answer.
– Vishwa Pratap
Nov 12 '18 at 16:22




@Chaudhary had you get the solution of your answer.
– Vishwa Pratap
Nov 12 '18 at 16:22












@VishwaPratap i post my answer, you can change the function as per your requirement.
– Chaudhary
Nov 13 '18 at 6:28




@VishwaPratap i post my answer, you can change the function as per your requirement.
– Chaudhary
Nov 13 '18 at 6:28












@Chaudhary thanks for your response
– Vishwa Pratap
Nov 13 '18 at 10:30




@Chaudhary thanks for your response
– Vishwa Pratap
Nov 13 '18 at 10:30












2 Answers
2






active

oldest

votes


















2














here is the html code.



<input type="file" #fileImportInput name="File Upload" (change)="csvChanged($event)" id="txtFileUpload">



below is my component code




const CSVConstants = {
tokenDelimeter: ",",
isHeaderPresentFlag: true,
validateHeaderAndRecordLengthFlag: true,
valildateFileExtenstionFlag: true,
}

public csvChanged(event) {
var files = event.target.files;

if (CSVConstants.validateHeaderAndRecordLengthFlag) {
if (!this.fileUtil.isCSVFile(files[0])) {
this.utilService.showToastMsg("error", "Please import valid .csv file");
this.fileReset();
return;
}
}

var input = event.target;
var reader = new FileReader();
reader.readAsText(input.files[0]);

reader.onload = (data) => {
let csvData: any = reader.result;
let csvRecordsArray = csvData.split(/rn|n/);

var headerLength = -1;
if (CSVConstants.isHeaderPresentFlag) {
let headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, CSVConstants.tokenDelimeter);
headerLength = headersRow.length;
}

this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
headerLength, CSVConstants.validateHeaderAndRecordLengthFlag, CSVConstants.tokenDelimeter);

if (this.csvRecords == null) {
//If control reached here it means csv file contains error, reset file.
this.fileReset();
}

/* Remove the file so that user can upload same one after making changes, otherwise change event
will not be called */
this.clearFile();

/* Remove the first header row */
this.csvRecords.splice(0, 1);

this.csvRecords.map((record: any) => {
this.external_contacts_arr.push({
email: record[0],
first_name: record[1],
last_name: record[2],
designation: record[3],
})
});
this.removeBlankRecords();
//document.getElementById(`${this.uniquePrefix}-other-tab`).click();
}

reader.onerror = () => {
this.utilService.showToastMsg("error", 'Unable to read ' + input.files[0]);
};
}





share|improve this answer





























    0














    You can use the below custom function to do the needful :



    private extractData(data) { // Input csv data to the function

    let csvData = data;
    let allTextLines = csvData.split(/rn|n/);
    let headers = allTextLines[0].split(',');
    let lines = ;

    for ( let i = 0; i < allTextLines.length; i++) {
    // split content based on comma
    let data = allTextLines[i].split(',');
    if (data.length == headers.length) {
    let tarr = ;
    for ( let j = 0; j < headers.length; j++) {
    tarr.push(data[j]);
    }
    lines.push(tarr);
    }
    }
    console.log(lines); //The data in the form of 2 dimensional array.
    }


    You can read the file inside the file listener function like this:



    function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    var file = files[0];
    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function(event){
    var csv = event.target.result; // Content of CSV file
    this.extractData(csv); //Here you can call the above function.
    }

    }


    Inside html use below code:



    <input type="file" (change)="handleFileSelect($event)"/>





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47673788%2fhow-to-import-csv-file-in-angular-4-and-stored-data-in-database%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      here is the html code.



      <input type="file" #fileImportInput name="File Upload" (change)="csvChanged($event)" id="txtFileUpload">



      below is my component code




      const CSVConstants = {
      tokenDelimeter: ",",
      isHeaderPresentFlag: true,
      validateHeaderAndRecordLengthFlag: true,
      valildateFileExtenstionFlag: true,
      }

      public csvChanged(event) {
      var files = event.target.files;

      if (CSVConstants.validateHeaderAndRecordLengthFlag) {
      if (!this.fileUtil.isCSVFile(files[0])) {
      this.utilService.showToastMsg("error", "Please import valid .csv file");
      this.fileReset();
      return;
      }
      }

      var input = event.target;
      var reader = new FileReader();
      reader.readAsText(input.files[0]);

      reader.onload = (data) => {
      let csvData: any = reader.result;
      let csvRecordsArray = csvData.split(/rn|n/);

      var headerLength = -1;
      if (CSVConstants.isHeaderPresentFlag) {
      let headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, CSVConstants.tokenDelimeter);
      headerLength = headersRow.length;
      }

      this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
      headerLength, CSVConstants.validateHeaderAndRecordLengthFlag, CSVConstants.tokenDelimeter);

      if (this.csvRecords == null) {
      //If control reached here it means csv file contains error, reset file.
      this.fileReset();
      }

      /* Remove the file so that user can upload same one after making changes, otherwise change event
      will not be called */
      this.clearFile();

      /* Remove the first header row */
      this.csvRecords.splice(0, 1);

      this.csvRecords.map((record: any) => {
      this.external_contacts_arr.push({
      email: record[0],
      first_name: record[1],
      last_name: record[2],
      designation: record[3],
      })
      });
      this.removeBlankRecords();
      //document.getElementById(`${this.uniquePrefix}-other-tab`).click();
      }

      reader.onerror = () => {
      this.utilService.showToastMsg("error", 'Unable to read ' + input.files[0]);
      };
      }





      share|improve this answer


























        2














        here is the html code.



        <input type="file" #fileImportInput name="File Upload" (change)="csvChanged($event)" id="txtFileUpload">



        below is my component code




        const CSVConstants = {
        tokenDelimeter: ",",
        isHeaderPresentFlag: true,
        validateHeaderAndRecordLengthFlag: true,
        valildateFileExtenstionFlag: true,
        }

        public csvChanged(event) {
        var files = event.target.files;

        if (CSVConstants.validateHeaderAndRecordLengthFlag) {
        if (!this.fileUtil.isCSVFile(files[0])) {
        this.utilService.showToastMsg("error", "Please import valid .csv file");
        this.fileReset();
        return;
        }
        }

        var input = event.target;
        var reader = new FileReader();
        reader.readAsText(input.files[0]);

        reader.onload = (data) => {
        let csvData: any = reader.result;
        let csvRecordsArray = csvData.split(/rn|n/);

        var headerLength = -1;
        if (CSVConstants.isHeaderPresentFlag) {
        let headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, CSVConstants.tokenDelimeter);
        headerLength = headersRow.length;
        }

        this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
        headerLength, CSVConstants.validateHeaderAndRecordLengthFlag, CSVConstants.tokenDelimeter);

        if (this.csvRecords == null) {
        //If control reached here it means csv file contains error, reset file.
        this.fileReset();
        }

        /* Remove the file so that user can upload same one after making changes, otherwise change event
        will not be called */
        this.clearFile();

        /* Remove the first header row */
        this.csvRecords.splice(0, 1);

        this.csvRecords.map((record: any) => {
        this.external_contacts_arr.push({
        email: record[0],
        first_name: record[1],
        last_name: record[2],
        designation: record[3],
        })
        });
        this.removeBlankRecords();
        //document.getElementById(`${this.uniquePrefix}-other-tab`).click();
        }

        reader.onerror = () => {
        this.utilService.showToastMsg("error", 'Unable to read ' + input.files[0]);
        };
        }





        share|improve this answer
























          2












          2








          2






          here is the html code.



          <input type="file" #fileImportInput name="File Upload" (change)="csvChanged($event)" id="txtFileUpload">



          below is my component code




          const CSVConstants = {
          tokenDelimeter: ",",
          isHeaderPresentFlag: true,
          validateHeaderAndRecordLengthFlag: true,
          valildateFileExtenstionFlag: true,
          }

          public csvChanged(event) {
          var files = event.target.files;

          if (CSVConstants.validateHeaderAndRecordLengthFlag) {
          if (!this.fileUtil.isCSVFile(files[0])) {
          this.utilService.showToastMsg("error", "Please import valid .csv file");
          this.fileReset();
          return;
          }
          }

          var input = event.target;
          var reader = new FileReader();
          reader.readAsText(input.files[0]);

          reader.onload = (data) => {
          let csvData: any = reader.result;
          let csvRecordsArray = csvData.split(/rn|n/);

          var headerLength = -1;
          if (CSVConstants.isHeaderPresentFlag) {
          let headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, CSVConstants.tokenDelimeter);
          headerLength = headersRow.length;
          }

          this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
          headerLength, CSVConstants.validateHeaderAndRecordLengthFlag, CSVConstants.tokenDelimeter);

          if (this.csvRecords == null) {
          //If control reached here it means csv file contains error, reset file.
          this.fileReset();
          }

          /* Remove the file so that user can upload same one after making changes, otherwise change event
          will not be called */
          this.clearFile();

          /* Remove the first header row */
          this.csvRecords.splice(0, 1);

          this.csvRecords.map((record: any) => {
          this.external_contacts_arr.push({
          email: record[0],
          first_name: record[1],
          last_name: record[2],
          designation: record[3],
          })
          });
          this.removeBlankRecords();
          //document.getElementById(`${this.uniquePrefix}-other-tab`).click();
          }

          reader.onerror = () => {
          this.utilService.showToastMsg("error", 'Unable to read ' + input.files[0]);
          };
          }





          share|improve this answer












          here is the html code.



          <input type="file" #fileImportInput name="File Upload" (change)="csvChanged($event)" id="txtFileUpload">



          below is my component code




          const CSVConstants = {
          tokenDelimeter: ",",
          isHeaderPresentFlag: true,
          validateHeaderAndRecordLengthFlag: true,
          valildateFileExtenstionFlag: true,
          }

          public csvChanged(event) {
          var files = event.target.files;

          if (CSVConstants.validateHeaderAndRecordLengthFlag) {
          if (!this.fileUtil.isCSVFile(files[0])) {
          this.utilService.showToastMsg("error", "Please import valid .csv file");
          this.fileReset();
          return;
          }
          }

          var input = event.target;
          var reader = new FileReader();
          reader.readAsText(input.files[0]);

          reader.onload = (data) => {
          let csvData: any = reader.result;
          let csvRecordsArray = csvData.split(/rn|n/);

          var headerLength = -1;
          if (CSVConstants.isHeaderPresentFlag) {
          let headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, CSVConstants.tokenDelimeter);
          headerLength = headersRow.length;
          }

          this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
          headerLength, CSVConstants.validateHeaderAndRecordLengthFlag, CSVConstants.tokenDelimeter);

          if (this.csvRecords == null) {
          //If control reached here it means csv file contains error, reset file.
          this.fileReset();
          }

          /* Remove the file so that user can upload same one after making changes, otherwise change event
          will not be called */
          this.clearFile();

          /* Remove the first header row */
          this.csvRecords.splice(0, 1);

          this.csvRecords.map((record: any) => {
          this.external_contacts_arr.push({
          email: record[0],
          first_name: record[1],
          last_name: record[2],
          designation: record[3],
          })
          });
          this.removeBlankRecords();
          //document.getElementById(`${this.uniquePrefix}-other-tab`).click();
          }

          reader.onerror = () => {
          this.utilService.showToastMsg("error", 'Unable to read ' + input.files[0]);
          };
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 13 '18 at 6:27









          Chaudhary

          829628




          829628

























              0














              You can use the below custom function to do the needful :



              private extractData(data) { // Input csv data to the function

              let csvData = data;
              let allTextLines = csvData.split(/rn|n/);
              let headers = allTextLines[0].split(',');
              let lines = ;

              for ( let i = 0; i < allTextLines.length; i++) {
              // split content based on comma
              let data = allTextLines[i].split(',');
              if (data.length == headers.length) {
              let tarr = ;
              for ( let j = 0; j < headers.length; j++) {
              tarr.push(data[j]);
              }
              lines.push(tarr);
              }
              }
              console.log(lines); //The data in the form of 2 dimensional array.
              }


              You can read the file inside the file listener function like this:



              function handleFileSelect(evt) {
              var files = evt.target.files; // FileList object
              var file = files[0];
              var reader = new FileReader();
              reader.readAsText(file);
              reader.onload = function(event){
              var csv = event.target.result; // Content of CSV file
              this.extractData(csv); //Here you can call the above function.
              }

              }


              Inside html use below code:



              <input type="file" (change)="handleFileSelect($event)"/>





              share|improve this answer


























                0














                You can use the below custom function to do the needful :



                private extractData(data) { // Input csv data to the function

                let csvData = data;
                let allTextLines = csvData.split(/rn|n/);
                let headers = allTextLines[0].split(',');
                let lines = ;

                for ( let i = 0; i < allTextLines.length; i++) {
                // split content based on comma
                let data = allTextLines[i].split(',');
                if (data.length == headers.length) {
                let tarr = ;
                for ( let j = 0; j < headers.length; j++) {
                tarr.push(data[j]);
                }
                lines.push(tarr);
                }
                }
                console.log(lines); //The data in the form of 2 dimensional array.
                }


                You can read the file inside the file listener function like this:



                function handleFileSelect(evt) {
                var files = evt.target.files; // FileList object
                var file = files[0];
                var reader = new FileReader();
                reader.readAsText(file);
                reader.onload = function(event){
                var csv = event.target.result; // Content of CSV file
                this.extractData(csv); //Here you can call the above function.
                }

                }


                Inside html use below code:



                <input type="file" (change)="handleFileSelect($event)"/>





                share|improve this answer
























                  0












                  0








                  0






                  You can use the below custom function to do the needful :



                  private extractData(data) { // Input csv data to the function

                  let csvData = data;
                  let allTextLines = csvData.split(/rn|n/);
                  let headers = allTextLines[0].split(',');
                  let lines = ;

                  for ( let i = 0; i < allTextLines.length; i++) {
                  // split content based on comma
                  let data = allTextLines[i].split(',');
                  if (data.length == headers.length) {
                  let tarr = ;
                  for ( let j = 0; j < headers.length; j++) {
                  tarr.push(data[j]);
                  }
                  lines.push(tarr);
                  }
                  }
                  console.log(lines); //The data in the form of 2 dimensional array.
                  }


                  You can read the file inside the file listener function like this:



                  function handleFileSelect(evt) {
                  var files = evt.target.files; // FileList object
                  var file = files[0];
                  var reader = new FileReader();
                  reader.readAsText(file);
                  reader.onload = function(event){
                  var csv = event.target.result; // Content of CSV file
                  this.extractData(csv); //Here you can call the above function.
                  }

                  }


                  Inside html use below code:



                  <input type="file" (change)="handleFileSelect($event)"/>





                  share|improve this answer












                  You can use the below custom function to do the needful :



                  private extractData(data) { // Input csv data to the function

                  let csvData = data;
                  let allTextLines = csvData.split(/rn|n/);
                  let headers = allTextLines[0].split(',');
                  let lines = ;

                  for ( let i = 0; i < allTextLines.length; i++) {
                  // split content based on comma
                  let data = allTextLines[i].split(',');
                  if (data.length == headers.length) {
                  let tarr = ;
                  for ( let j = 0; j < headers.length; j++) {
                  tarr.push(data[j]);
                  }
                  lines.push(tarr);
                  }
                  }
                  console.log(lines); //The data in the form of 2 dimensional array.
                  }


                  You can read the file inside the file listener function like this:



                  function handleFileSelect(evt) {
                  var files = evt.target.files; // FileList object
                  var file = files[0];
                  var reader = new FileReader();
                  reader.readAsText(file);
                  reader.onload = function(event){
                  var csv = event.target.result; // Content of CSV file
                  this.extractData(csv); //Here you can call the above function.
                  }

                  }


                  Inside html use below code:



                  <input type="file" (change)="handleFileSelect($event)"/>






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 13 '18 at 8:03









                  Prasan Karunarathne

                  1925




                  1925






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47673788%2fhow-to-import-csv-file-in-angular-4-and-stored-data-in-database%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Xamarin.iOS Cant Deploy on Iphone

                      Glorious Revolution

                      Dulmage-Mendelsohn matrix decomposition in Python