I am new to angular , I learned myself and implemented following code , but this.data is always shows as ‘undefined’.
this.data is always coming has ‘undefined’ – Please let me know what mistake I am doing,
Functionality of my code :- It simple angular page where I upload the .csv file with 5 headers and some data in these columns in the file. After I click on upload same .csv file should be saved to server.
Below is my code, here I am passing filename and file content (in json format) to my .net webAPI, my webapi will save the file to server.
- Please let me know why the this.data is always shows as undefined
- To save the new file to server, what ever I have implemented is that correct approach ?
this is my web API code :-
public class SaveModel
{
public string FileName { get; set; }
public string DestinationPath { get; set; }
public IEnumerable Lines { get; set; }
}
[Route("FileSave")]
public ActionResult FileSave([FromBody] SaveModel model)
{
try
{
this.SaveOperation(model.FileName, model.DestinationPath, model.Lines);
return this.Ok();
}
catch (Exception ex)
{
this.logger.Error("File Save failed.", ex);
}
}
public void SaveOperation(string filename, string destinationPath, IEnumerable lines)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var line in lines)
{
stringBuilder.AppendLine(line);
}
var byteArray = Encoding.UTF8.GetBytes(stringBuilder.ToString());
this.CreateCSVFile(destinationPath, filename, new MemoryStream(byteArray));
}
CreateCSVFile // this is my code where it calls server and place the .csv file
HTML Code :
system
Below is my componenet code :-
/*fileName = '';*/
fileSelected = false;
invalidFileType = false;
file: File = null; // Variable to store file
data: any;
jsonData: any;
displayError: boolean;
errorText: string;
responseData: any;
@ViewChild('fileUpload') fileUpload: ElementRef;
/*fileName = '';*/
fileSelected = false;
invalidFileType = false;
file: File = null; // Variable to store file
data: any;
jsonData: any;
displayError: boolean;
errorText: string;
responseData: any;
@ViewChild('fileUpload') fileUpload: ElementRef;
Reset(form) {
this.fileUpload.nativeElement.value = "";
console.log("Reset completed");
}
UploadFile(filevalue) {
const reqbody = {
filename: this.file.name,
lines: JSON.stringify(this.data)
};
var route = "FileSave";
this.dataService.post(reqbody, route).subscribe(
(data: any[]) => {
console.log("Response data: " + data);
LoggerService.success(`File successfully uploaded to server`, true, false);
this.responseData = data;
},
(error: Response) => {
this.displayError = true;
this.errorText = `Error saving API service ${error.status}`;
});
}
onFileChange(event: any): void {
this.file = event.target.files[0];
this.fileSelected = true;
this.invalidFileType = false;
this.readFile();
}
readFile(): void {
fileReader.onload = (e: any) => {
const binaryString = e.target.result;
console.log(binaryString);
const workBook = XLSX.read(binaryString, { type: 'binary' });
const workSheetName = workBook.SheetNames[0];
const workSheet = workBook.Sheets[workSheetName];
// Parse the Excel data into JSON format
this.data = XLSX.utils.sheet_to_json(workSheet);
console.log(this.data);
}
}
}
Kumar AUPosted Nov 26, 2023, 9:00 PM
Thank you Prasad for your help, this worked fine - I missed to add this line in my code - fileReader.readAsBinaryString(this.file);
Prasad RaveendranPosted Nov 26, 2023, 8:15 PM
Here's a corrected version of the
readFile()method:Changes made:
FileReaderinstance.onloadevent handler to thefileReader.readAsBinaryStringmethod to read the content of the selected file.Ensure that the
XLSXmodule is properly imported into your Angular component, as it seems you are using it to read Excel files. Also, you can call theUploadFilemethod within theonloadevent handler if you want to trigger the file upload after reading it successfully.Regarding your second question about saving the file to the server: The approach seems reasonable. You are sending the filename and file content (in JSON format) to your .NET WebAPI, which then processes this information in the
FileSaveaction. This action initiates theSaveOperationmethod to create the CSV file and save it on the server using a provided path and filename.Ensure that your .NET backend is correctly configured to receive and handle the data sent from the Angular frontend. Also, verify the server-side implementation (
SaveOperationmethod andCreateCSVFilefunction) to make sure the file saving logic is correctly executed based on the received data.Always perform appropriate error handling and validation, especially when dealing with file uploads and server-side operations.