以下是我的代码,我基本上是尝试使用我的应用程序发送csv和xlxs文件。虽然,一切看起来都对我来说,我仍然无法处理并将文件发送到我的后端。当我将文件发送到后端时,我从后端收到响应,因为"没有上传文件"虽然它使用邮差很好。我在代码中遗漏了什么?
文件组件
export class FileUploadComponent {
constructor(private service:FileUploadService) {
this.service.progress$.subscribe(
data => {
console.log('progress = '+data);
});
}
onChange(event) {
console.log('onChange');
let files = event.target.files;
console.log(files);
this.service.makeFileRequest('http://localhost:9000/api/v1/fileUpload/country', [], files).subscribe(() => {
console.log('sent');
});
}
}
的FileService
export class FileUploadService {
public progress$;
public progressObserver;
public progress : number;
constructor (private auth:AuthenticationService) {
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.setRequestHeader('Authorization', 'Bearer ' + this.auth.token);
xhr.send(formData);
});
}
}