I need to upload a file and send some json along with it, I have this function:
POST_formData(url, data) {
var headers = new Headers(), authtoken = l
Template:
UPD: Angular 5 - HttpClient + Typescript
onFileUpload(event: EventTarget) {
const eventObj: MSInputMethodContext = event;
const target: HTMLInputElement = eventObj.target;
const files: FileList = target.files;
const formData: FormData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
// POST
this.httpClient.post(uploadUrl, formData).subscribe(...);
}
old Http lib - before Angular 4.3:
fileChange(event) {
let files = event.target.files;
if (files.length > 0) {
let formData: FormData = new FormData();
for (let file of files) {
formData.append('files', file, file.name);
}
let headers = new Headers();
headers.set('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(uploadURL, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => {
// Consume Files
// ..
console.log('uploaded and processed files');
},
error => console.log(error),
() => {
this.sleep(1000).then(() =>
// .. Post Upload Delayed Action
)
});
}
}