Angular 4 - Upload CSV - html

I am making an Angular4
I have a button that converts data to a csv file with header.
Now I want to do it the other way around, I want to upload a csv file.
So for testing, I make an object and make a csv file from it, and then I want to click on a button and upload that file and get the same result.
I found an angular module to export csv, but I can't find one that does it the other way around. Can someone help me with that?
This is my code:
test.ts
import { Component, OnInit} from '#angular/core';
import { Angular2Csv } from 'angular2-csv/Angular2-csv';
import {Unit} from "../../../_shared/unit";
#Component({
moduleId: module.id,
templateUrl: 'test.component.html',
styleUrls: ['./test.css']
})
export class TestComponent implements OnInit {
ngOnInit() {}
public export() {
// Unit (id,name,description)
var data = [new Unit(1,"Unit1","This is unit 1!")];
var options = {
fieldSeparator: ';',
quoteStrings: '"',
decimalseparator: ',',
showLabels: true,
useBom: true
};
new Angular2Csv(data, "data", options);
}
public import(){}
}
test.html
<button (click)="export()">Download CSV</button>
<button (click)="import()">Upload CSV</button>

You can achieve the functionality using a custom function, Try this :
private extractData(data) { // Input csv data to the function
let csvData = data;
let allTextLines = csvData.split(/\r\n|\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 find the detailed post here: http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html#.WWxu9XV97OQ
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 do this:
<input type="file" (change)="handleFileSelect($event)"/>

Related

Html to Pdf Format Angular

Hello i want to convert from html to pdf format and send it as a file to my backend, so i can save it in my server, i tried using jspdf but its not working
SendMail() {
var doc = new jspdf();
doc.fromHTML('<h1>Hello World!</h1>', 20, 20);
var blob = new Blob([doc.output("blob")], { type: "application/pdf" });
let lruta = 'report/' + 'test';
this.uploaderService.uploadfile(blob, lruta).subscribe(
response => {
this.fetcher = response;
this.blockUI.stop();
}, error => {
this.blockUI.stop();
}
);
}
This is my service UploadFile
uploadfile(cabecera, ruta) {
const formData = new FormData();
formData.append('file', cabecera[0]);
formData.append('ruta', ruta);
return this._http.post(this.apiUrl + this.serviceUrl + 'gestion/uploadrevision', formData);
}
When i replace blob with this.file in my this.uploaderService.uploadfile
it works, but i dont want to download and upload my file
file: any;
onFileChange(event) {
this.file = event.target.files;
}

Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app

I have installed the json-server in my Angular app which enables me to save a form (filled by the user) via a fake json API into a json file:
{
"extracts": [
{
"contentName": "xxx",
"contentType": "xxx",
"contentToStore": "xxx",
"id": 1
}
]
}
I can also see the results at my http://localhost:3000/extracts
In my html template, my form is submitted:
<form #postForm="ngForm" (ngSubmit)="onSubmitExtractions(postForm.value)">
In the corresponding component, I have written this code:
onSubmitExtractions(postData: Post) {
this
.dbService
.submitExtractions(postData)
.subscribe(
postData => {
this.jsonPosts.push(postData);
}
);
this
.dbService
.downloadExtractions(postData);
}
The first snippet writes to the json file, with this code in the service script:
submitExtractions(post: Post): Observable<Post> {
return this.httpClient.post<Post>(this.apiUrl, post, httpOptions);
}
This works fine and I get the results in a json file (fake json server database) and the second snippet is supposed to download this file whose code in the service script is this:
downloadExtractions(post: Post) {
const blob = new Blob([JSON.stringify(post, null, 2)], { type: 'application/json' });
if (blob) {
this.downloaded = 'The blob contains ' + blob.size + ' byte!';
} else {
this.downloaded = 'The download failed!';
}
}
What am I missing in ths code in order to actually download the json content? How do I download this content as a csv or json or even a text file?
Please try this solution. It is using the same blob just with some constant data.
in html
<a [href]="fileUrl" download="file.txt">DownloadFile</a>
in component.ts
export class AppComponent implements OnInit {
name = 'Angular 5';
fileUrl;
constructor(private sanitizer: DomSanitizer) { }
ngOnInit() {
const data = 'some text';
const blob = new Blob([data], { type: 'application/octet-stream' });
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
}
}
For reference, please visit:
https://stackblitz.com/edit/angular-blob-file-download-text-file?file=app%2Fapp.component.ts

issue in json data fetching and rendering in nextjs

I am trying out a small sample in nextjs. All that the proj does is to fetch json data from a file and try displaying it in list of a component. But the behavior is weird. Its getting into infinite loop and I have no clue what's wrong. Could some one take a look at https://github.com/SamplesForMurthy/sampleCode and help me figure out what the issue is? Not able to fetch the data nor I am able to display.
I cloned and fixed. You don't need to use fs.readFileSync here, or fs at all for that matter. You can simply import the .json file as an arbitrarily named variable then map it out.
Here is how I got the data rendering:
import React from 'react';
import testData from '../TestData/SampleData.json';
import SampleParentComponent from '../components/SampleParentComponent';
function TestPage({ filecontent }) {
console.log(`filecontent: ${filecontent}`);
return (
<div>
<SampleParentComponent data={filecontent}></SampleParentComponent>
</div>
);
}
export const getStaticProps = async ctx => {
console.log(ctx.query);
const filecontent = await testData;
return {
props: { filecontent }
};
};
export default TestPage;
/**
* (property) filecontent: {
data: {
seqNo: number;
contactName: string;
}[];
}
*/

Angular AoT build import local json file

In my first angular app I have a service who import a json file to load some data (I need to load it synchronously, before the DOM).
In develop mode, when I modify the json file, the cli rebuild the app and all work like a charm.
Unluckily on build -prod modifying the json in my 'dist/assets' directory does not update the app. The compiler embed json into my main-es2015.js and do not reference anymore on external file.
works.service.ts:
import { Injectable } from '#angular/core';
import PICTURES from '../../assets/pictures.json';
#Injectable({
providedIn: 'root'
})
export class WorksService {
pictures: any;
constructor() {
this.pictures = PICTURES
}
getWorks() { return this.pictures; }
getSingleWork(id: string) {
return this.pictures.find(i => i.id === id);}
getPreviousWork(id: string) {
const index = this.pictures.findIndex(i => i.id === id) - 1;
if (typeof this.pictures[index] === 'undefined') {
// cycle to start
return this.pictures[this.pictures.length-1]
}
else {
return this.pictures[index]
}
}
getNextWork(id: string) {
const index = this.pictures.findIndex(i => i.id === id) + 1;
if (typeof this.pictures[index] === 'undefined') {
// cycle to start
return this.pictures[0]
}
else {
return this.pictures[index]
}
}
}
I tried to use httpClient or to load the json dynamically:
this.pictures = import('../../assets/pictures.json')
but the page is loaded before the file and I cant figure out how to load it before.
It will be better to create a new pictures.ts file and put it into this file your JSON as an object.
// pictures.ts
export const pictures: any = { "name":"John", "age":30, "car":null };
after that import this const and use it into your components.
// pictures.component.ts
import { pictures } from "./pictures";

compress image on upload in angular

I wanted to upload images to products, and users. So im converting the image to base64 string and sending it. But when the selected image is large, the image is not getting uploaded as the base64 string is too large.
Here is the code:
Html
<input type="file" (change)="onFileSelected($event)">
<button type="submit" title="upload" (click)="uploadImage()"></button>
TS File
onFileSelected(event){
var files = event.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload =this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.base64textString= btoa(binaryString);
console.log(btoa(binaryString));
}
Im just accepting the images on selection. So, is there any way to comress the image after selection or a way to reduce the base64 string so the image gets uploaded.
Thanks!! in advance.
In Angular you can upload image wihtout converting it into base64. Check this...
import { ViewChild } from '#angular/core';
export class yourComponent {
#ViewChild('fileInput') fileInput;
.
.
.
}
uploadImage(){
let fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
console.log(fileBrowser.files[0]);
const formData = new FormData();
formData.append("userId", this.userId ); //appending userId in formData
formData.append("image", fileBrowser.files[0]); //appending image in formData
this.apiService.UploadImageMethod(formData)
.subscribe(
response=>{
console.log(response);
if(response.status == 'success'){
console.log(response);
}
},
err => {
this.imageErrorMsg = <any>err.message;
console.log(this.imageErrorMsg);
}
);
}
}
HTML:
<input type="file" id="fileInput" (click)="hideErrorMsg()" accept="image/*" #fileInput>
In API, you can get image data this way. (Php)
UploadImageMethod(){
$fileName = request()->image->getClientOriginalExtension();
$ext = strtolower(request()->image->getClientOriginalExtension());
}
Good Luck!!!