cancel
Showing results for 
Search instead for 
Did you mean: 

Upload csv to dynamic table with JS fileUploader

0 Kudos
359

Dear, I encounter the following problem when wanting to upload a csv file and display it in a dynamic table:

1) ---- In the index I have declared the following libraries with the respective view
<!DOCTYPE HTML>
<html>
	<head>
		<title>CMPC Client</title>
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<link rel="icon" type="image/png" href="just-bi16x16.png"/>
		<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
		<link rel="stylesheet" type="text/css" href="css/new.css">
		<script src="resources/sap-ui-core.js"				
				id="sap-ui-bootstrap"
				data-sap-ui-libs="sap.m,sap.ui.commons, sap.ui.table, sap.ui.ux3, sap.ui.core, sap.ui.unified,sap.suite.ui.commons,
				sap.ui.layout"
				data-sap-ui-theme="sap_bluecrystal"
				data-sap-ui-xx-bindingSyntax = "complex"
				data-sap-ui-preload = ""
				data-sap-ui-resourceroots = '{
					"demo": "./"
				}'>
		</script>
		<!-- only load the mobile lib "sap.m" and the "sap_bluecrystal" theme -->
		<script>
				sap.ui.localResources("cmpcclient");
				var app = new sap.m.App({initialPage:"idLogo1"});
				var page = sap.ui.view({id:"idLogo1", viewName:"cmpcclient.Logo", type:sap.ui.core.mvc.ViewType.JS});
				var page2 = sap.ui.view({id:"idLogo2", viewName:"cmpcclient.form", type:sap.ui.core.mvc.ViewType.JS});
				
				
				app.addPage(page);
				app.addPage(page2);
				app.placeAt("content");
		</script>
	
	</head>
	<body role="application">
		<div id="content"></div>
	</body>
</html>
2)-------    In the view I have configured the following:  ---------------
sap.ui.define([
	'jquery.sap.global',
	"sap/ui/model/Filter",
	"sap/ui/unified/FileUploader",
	"sap/ui/core/mvc/Controller",
	"sap/ui/model/json/JSONModel",
	"sap/m/MessageToast",
	"sap/m/Column",
	"sap/m/ColumnListItem",
	"sap/m/Label",
	"sap/m/Text",
	"sap/m/TabContainerItem",
	"sap/m/MessageBox", 
	]),
sap.ui.jsview("cmpcclient.form", {
	/** Specifies the Controller belonging to this View. 
	* In the case that it is not implemented, or that "null" is returned, this View does not have a Controller.
	* @memberOf cmpcclient.form
	*/ 
	getControllerName : function() {
		return "cmpcclient.form";
	},
	/** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed. 
	* Since the Controller is given to this method, its event handlers can be attached right away. 
	* @memberOf cmpcclient.form
	*/ 
	createContent : function(oController) {
		var oLabel = new sap.m.Label("IdLabel1");
		
		//Asignaciones a Cajas
		
		
		var cajaPrincipal = new sap.ui.commons.layout.MatrixLayout("Matrix4", {
			layoutFixed: true,
			columns: 5,
			widths: ['300px', '300px', '300px', '200px', '200px']
		}).addStyleClass("divInput");
		// 1.Row
		
		 var seccionTitulo = new sap.ui.commons.layout.MatrixLayoutCell();
		seccionTitulo.setVAlign(sap.ui.commons.layout.VAlign.bottom);
		seccionTitulo.setColSpan(5)
		
		cajaPrincipal.createRow({height: "100px"},seccionTitulo);;
		
		
		var oMLC2 = new sap.ui.commons.layout.MatrixLayoutCell("caja1");
		oMLC2.setVAlign(sap.ui.commons.layout.VAlign.bottom);
		oMLC2.setColSpan(5);
		
		cajaPrincipal.createRow({height: "100px"},oMLC2);
		
	
		
		var tableDiv = new sap.ui.commons.layout.MatrixLayoutCell("tableDiv").addStyleClass("table");
		tableDiv.setVAlign(sap.ui.commons.layout.VAlign.bottom);
		tableDiv.setColSpan(5)
		
		cajaPrincipal.createRow({height: "auto",width:"100%"},tableDiv);
		
		
	//FIN Asignaciones a Cajas
		
	//Header
	//Titulo
		var component = new sap.ui.commons.TextView("TV-Head").addStyleClass("component-title");
		component.setText("Carga de Datos");
		component.setDesign(sap.ui.commons.TextViewDesign.H3);
		seccionTitulo.addContent(component);	
		
		
	//Creamos lista de Items
		var oListBox1 = new sap.ui.commons.ListBox("Cities",{
			items:[
			       new sap.ui.core.ListItem({id:"Ciudad1", text:"Orlando", additionalText:"bello"}),
			       new sap.ui.core.ListItem({id:"Ciudad2", text:"España", additionalText:"bello"}),
			       new sap.ui.core.ListItem({id:"Ciudad3", text:"Paraguay", additionalText:"maso"}),
			       new sap.ui.core.ListItem({id:"Ciudad4", text:"Argentina", additionalText:"copado"}),
			       ]
		});
		
		
		var oComboBox1 = new sap.ui.commons.ComboBox("ComboBoxC",{
			tooltip: "ciudad",
			displaySecondaryValues: true,
			value: "Prueba1",
			"association:listBox": oListBox1			
		}).addStyleClass("combBox");
		
		oMLC2.addContent(oComboBox1);
		
	   
	    //suba de archivos
		
		var oFileUploader = new sap.ui.unified.FileUploader({
			id:"fileUpload",
            name: "simpleUploader", 
            sendXHR: true,
            uploadUrl:"upload/",
            useMultipart: false,
            change:[oController.handleUpload,oController],                             
        });
	    oMLC2.addContent(oFileUploader);
	   
	   
	    var oButton = new sap.m.Button({width:"10rem",
            text:"Enviar",
            type:"Emphasized",
           
	    });
	    oMLC2.addContent(oButton);
	   
	   
	    //Logo
	    var oImg = new sap.ui.commons.Image({
	    	id: 'img-pic',
	    	src : './logo-cmpc.png',
	    	alt: 'CMPC',
	    }).addStyleClass("logo-cmpc");
	    seccionTitulo.addContent(oImg);
	   
	   
	    //Comienzo Table
	    var oTable =  new sap.ui.table.Table("TableInvoice", { editable:  false,
	    	
	       
	    	
	    }); 
		tableDiv.addContent(oTable);
		
		
 
		
	    //Fin Header
	   
	   
		//Retornamos todo el DIV
		return cajaPrincipal;
	
		
		
		var oPage = new sap.m.Page({
			title: "Simple Animal List",
			showNavButton: true,
            navButtonPress: function(){ oController.handleNavBack(); },
			content: [Titulo,
			          cajaPrincipal,
			          oAppHeader,
			          oTable
			]
		});
			
	 		
	 		return oPage;
		}
});



-------------------------in the controller the following code:-----------------------------------------------------



sap.ui.define([
	"jquery.sap.global",
	"sap/ui/model/Filter",
	"sap/ui/unified/FileUploader",
	"sap/ui/core/mvc/Controller",
	"sap/ui/model/json/JSONModel",
	"sap/m/MessageToast",
	"sap/m/Column",
	"sap/m/ColumnListItem",
	"sap/m/Label",
	"sap/m/Text",
	"sap/m/TabContainerItem",
	"sap/m/MessageBox", 
	], function(jQuery, Controller, Filter, JSONModel, Column, ColumnListItem, Label, Text){  


	
var cController = Controller.extend("cmpcclient.form", {
	
onInit: function(oEvent){
		var oModel = new sap.ui.model.json.JSONModel();
		oModel.setSizeLimit(10000);
		sap.ui.getCore().setModel(oModel);
		var oUploader = this.getView().byId("fileUploader");
		oUploader.addEventDelegate({
			onAfterRendering: function(){
				this.setFileType(['csv']);
			}
		},oUploader);
	},
	




handleUpload: function(oEvent) {
	var that = this
	var oFileToRead = oEvent.getParameters().files["0"];
	if(oFileToRead && window.FileReader){ 
		var reader = new FileReader();
		// Read file into memory as UTF-8
		// Handle errors load
		reader.onload = function(evt) {
            var strCSV = evt.target.result; //string in CSV 
            that.csvJSON(strCSV);
          };
          reader.readAsText(oFileToRead);
		}
	},




	csvJSON: function(csv) {
	    var lines = csv.split("\n");
	    var result = [];
	    var headers = lines[0].split(",");
	    for (var i = 1; i < lines.length; i++) {
	      var obj = {};
	      var currentline = lines[i].split(",");
	      for (var j = 0; j < headers.length; j++) {
	        obj[headers[j]] = currentline[j];
	      }
	      result.push(obj);
	    }
	    var oStringResult = JSON.stringify(result);
	    var oFinalResult = JSON.parse(oStringResult.replace(/\\r/g, ""));
	    //return result; //JavaScript object
	    //sap.ui.getCore().getModel().setProperty("/", oFinalResult);
	    this.generateTable();
	  },
	  
	  generateTable: function() {
          var oTable = this.getView().byId("TableInvoice");
          var oModel = sap.ui.getCore().getModel();
          var oModelData = oModel.getProperty("/");
          var oColumns = Object.keys(oModelData[0]);
          var oColumnNames = [];
          $.each(oColumns, function(i, value) {
            oColumnNames.push({
              Text: oColumns[i]
            });
          });
          oModel.setProperty("/columnNames", oColumnNames);
          var oTemplate = new Column({
            header: new Label({
              text: "{Text}"
            })
          });
          oTable.bindAggregation("columns", "/columnNames", oTemplate);
          var oItemTemplate = new ColumnListItem();
          var oTableHeaders = oTable.getColumns();
          $.each(oTableHeaders, function(j, value) {
            var oHeaderName = oTableHeaders[j].getHeader().getText();
            oItemTemplate.addCell(new Text({
              text: "{" + oHeaderName + "}"
            }));
          });
          oTable.bindItems("/", oItemTemplate);
        }




	
	});
	return cController;
});

4) -------------------------------------------------------------------------------

The error that returns to me when uploading the csv file is the following:


Cannot read property 'setProperty' of undefined
    at f.csvJSON (form.controller.js?eval:64)
    at FileReader.reader.onload (form.controller.js?eval:42)








Accepted Solutions (0)

Answers (3)

Answers (3)

0 Kudos

Dear I throw the following error,

ncaught TypeError: this.oTable.bindAggregation is not a function
 at constructor.generateTable (Form.controller.js? eval: 134)
 at constructor.csvJSON (Form.controller.js? eval: 114)
 at FileReader.reader.onload (Form.controller.js? eval: 77)
0 Kudos

Dear good morning, thank you for your response, I was able to solve it by adding the library where that function is located, if I have doubts since I do not recognize the table, when debuting it I figure as undefined,

former_member540067
Active Participant
0 Kudos

Change your onInit Code from :

var oModel = new sap.ui.model.json.JSONModel();

to

this.oModel = new sap.ui.model.json.JSONModel();

and in generateTable method, use this.oModel instead of oModel