2017-08-01 150 views
4

我有一個需要上傳一個.CSV文件,並在我的組件中讀取它們,我已經通過這個博客,但它有一個.CSV文件存儲在一個特定的位置,我想上傳.CSV文件並在裏面讀取它們我的組件。我該怎麼做如何上傳CSV文件並使用angular2讀取它們?

我們可以使用插件嗎?如果不是的話,我們如何才能實現這一目標。

這就是我試圖

視圖

<input type="file" name="File Upload" id="txtFileUpload" 
     (change)="changeListener($event)" 
     accept=".csv"/> 

組件

changeListener($event:Response): void { 
    debugger; 
    // i am not able to get the data in the CSV file 
    } 

中的ChangeListener(),我不能夠湯姆獲得的內容代碼.CSV文件,任何人都可以幫助我解決這個問題嗎?

謝謝

+0

這與[這個問題(https://開頭計算器的.com /問題/ 40214772 /文件上傳入 - 角-2)。你可以用[這個笨蛋的例子]來測試(https://plnkr.co/edit/S2jycxeyLLLFu5wFDtA8?p=preview) – 0mpurdy

+1

https://coderexample.com/reading-csv-file-using-javascript/完全使用pappa parse來閱讀csv – jemiloii

回答

1

我在我的應用程序上做了一個上傳功能。希望它可以幫助

這裏是我的成分在我的樣本上傳功能

uploadDatasource(fileInput: any) { 

let file = fileInput.target.files[0]; 
let fileName = file.name; 


let payload = { 
    file, 
} 

let formData: FormData = new FormData(); 
formData.append('file',file,file.name); 


this.DsListService.uploadDatasource(formData) 
    .subscribe(
    response => { 
     console.log('UPLOADING success'); 


    }, 
    error => { 
     console.log('error',error) 
    }); 

} 

這裏是我的服務類

import { Injectable } from '@angular/core'; 
import { Headers, Http, RequestOptions, Response, URLSearchParams } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 
import { Config } from '../config/config'; 

@Injectable() 
export class DsListService { 

    private config = new Config; 

    constructor(private http: Http) { } 


    uploadDatasource(payload): Observable<any[]> { 
    let headers = new Headers(); 

    headers.append('Accept', 'application/json, text/plain,'); 
    let options = new RequestOptions({ headers: headers }); 


    return this.http.post(`API_UPLOAD_PATH`,payload, options) 
     .map((res: Response) => { 
     let data = res.json(); 
     return data; 
     }) 
     .catch(error => Observable.throw(error)) 

    } 
} 

,這裏是我的html

<input type="file" [(ngModel)]="Model.datasourcelistdata" name="datasource_upload" id="datasource_upload" accept=".xlsx,.xls,.csv" ngf-max-size="20MB" fd-input (change)="uploadDatasource($event)" /> 
+0

我不想將其上傳到文件位置,我想在angular2本身中處理上載的.CSV文件。我該怎麼做?任何想法 –

+0

你不能使用Angular2操作上傳的數據/ csv,因爲前端的東西不能處理文件系統。你需要在服務器上構建你的邏輯,比如'nodejs','php','python'等。 – vistajess

1

上傳CSV文件到位置並獲取位置URL和上傳的csv文件名稱並使用我創建的此服務。

import { Injectable, Inject} from '@angular/core'; 
import { Http } from '@angular/http'; 
import {HttpService} from './http.service'; 
@Injectable() 
export class CSVSERVICE { 
    csvUrl: string = './csv_upload?id='; // URL to web API 
    csvData: any[] = []; 

    constructor (private http: Http) {} 

    readCsvData (fileName) { 
    return this.http.get(this.csvUrl + fileName) 
    .map(
     (idata) => { 
     let csvData = idata['_body'] || ''; 
    let allTextLines = csvData.split(/\r?\n|\r/); 
    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]); 
      } 

// log each row to see output and 
      console.log(tarr); 
      lines.push(tarr); 
     } 
    } 
    return lines; 
     }, // this.extractData, 
     err => this.handleError(err) 
    ); 
    } 



    private handleError (error: any) { 
    let errMsg = (error.message) ? error.message : 
     error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
    console.error(errMsg); 
    return errMsg; 
    } 
} 
6

將您的csv文件上傳到某個位置並獲取csv文件數據。請試試這個: -

Component.html: -

<input type="file" class="upload" (change)="changeListener($event.target.files)"> 

Component.ts: -

public changeListener(files: FileList){ 
    console.log(files); 
    if(files && files.length > 0) { 
    let file : File = files.item(0); 
     console.log(file.name); 
     console.log(file.size); 
     console.log(file.type); 
     let reader: FileReader = new FileReader(); 
     reader.readAsText(file); 
     reader.onload = (e) => { 
      let csv: string = reader.result; 
      console.log(csv); 
     } 
    } 
}