i am doing a file upload component. I need to submit a formdata object for that. I cant append a file or anything to formdata object for some reason. The following is my code;
import {Component, ElementRef,
ViewChild,EventEmitter, Input, Output, OnInit, OnDestroy} from "@angular/core";
import { UploadService } from './file-upload.service';
@Component({
selector: 'dbs-file-upload',
template: ` <div class="file-upload-wrapper">
<dbs-input [(ngModel)]="fileName" type="text" class="input-long" placeholder='{{"upload.file_input_placeholder" | translate}}' readonly></dbs-input>
<button class="btn-browse" for="files">
<label for="files">Browse</label>
<input type="file" (change)="onChange($event)"
[multiple]="multiple"
id="files" style="visibility:hidden;"
accept=".csv, text/xml, application/xml, application/vnd.ms-excel"
#fileInput>
<img src="/images/ico_browse_plus.png">
</button>
</div>`,
styleUrls: ['./file-upload.component.scss'],
providers: [UploadService]
})
export class FileUploadComponent implements OnInit{
@Input() fileName: string;
@Output() onSelect = new EventEmitter<any>();
@Input() multiple: boolean = false;
// @ViewChild('fileInput') inputEl: ElementRef;
constructor(private service: UploadService) {
// this.service.progress.subscribe(data => {
// // console.log(data);
// })
}
ngOnInit() {
}
onChange(event) {
var files = event.srcElement.files;
console.log('filesss', files);
if (files.length > 0) {
let fd: FormData = new FormData();
let xhr: XMLHttpRequest = new XMLHttpRequest();
console.log(xhr, 'FAFAAJHAKB');
for (let file of files) {
fd.append('files', file, file.name);
}
console.log(fd, 'FROM COMPAKAP');
}
this.fileName = files[0].name;
this.onSelect.emit(files[0]);
// this.service.makeFileRequest('http://localhost:8080/mock/upload-file-list.json', [], files).subscribe(() => {
// console.log('whyy why');
// })
}
}
Am trying to append a file object, when i console.log, the formdata object contains nothing. by right it should get the appended file atleast. can someone tell me what going wrong here? Thanks in advance. First time in my life i am doing a file upload code.
Here it is.
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
/** No need to include Content-Type in Angular 4 */
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(`${this.apiEndPoint}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
use this code inside onChange method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With