正在上传excel文件

问题描述 投票:2回答:1

我对angular非常新,以及如何实现上传excel文件。我试着按照下面的教程进行操作,但是我收到了一个错误

self.context.onChange不是一个函数

在我的country_table组件中。我不知道我的做法是否正确。

FileUpload组件

@Component({
    selector: 'file',
    templateUrl: '../Country/country_table.html',
    providers: [ FileUploadService ]
})
export class FileUploadComponent {
    constructor(private service:FileUploadService) {
        this.service.progress$.subscribe(
            data => {
                console.log('progress = '+data);
            });
    }

    onChange(event) {
        console.log('onChange');
        var files = event.srcElement.files;
        console.log(files);
        this.service.makeFileRequest('http://localhost:9000/upload/country', [], files).subscribe(() => {
            console.log('sent');
        });
    }
}

FileUploadService

@Injectable()
export class FileUploadService {
   public progress$;
   public progressObserver;
   public progress : number;
   constructor () {
        this.progress$ = Observable.create(observer => {
            this.progressObserver = observer
        }).share();
   }

   makeFileRequest (url: string, params: string[], files: File[]) {
        return Observable.create(observer => {
            let formData: FormData = new FormData(),
                xhr: XMLHttpRequest = new XMLHttpRequest();

            for (let i = 0; i < files.length; i++) {
                formData.append("uploads[]", files[i], files[i].name);
            }

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        observer.next(JSON.parse(xhr.response));
                        observer.complete();
                    } else {
                        observer.error(xhr.response);
                    }
                }
            };

            xhr.upload.onprogress = (event) => {
                this.progress = Math.round(event.loaded / event.total * 100);

                this.progressObserver.next(this.progress);
            };

            xhr.open('POST', url, true);
            xhr.send(formData);
        });
    }
}

country_table.html

angular
1个回答
1
投票

您需要使用组件内定义的标签。所以在这种情况下

`<file></file>`

另一方面,要从事件中获取文件,您必须使用event.target

var files = event.target.files;
© www.soinside.com 2019 - 2024. All rights reserved.