I am unable to set headers to my request URL. Request has to send the upload file object, request JSON and headers required for authorization. The request doesn't append with the headers so the api sending me 401 unauthorized response back. Mine is a Angular 7 Application. I am using @angular/http for header building. Please find html & ts the code below.
Any quick fix will helps me a lot.
HTML code
<div class="font-weight-bold text-center pageSpacing">
Thanks America <img src="assets/images/add-icon.png"
style="width: 3%; float: right;" class="pointer"
(click)="openWindowCustomClass(content)">
</div>
<ng-template #content let-modal>
<div class="modal-header" style="border-bottom: 0px;">
<div class="pointer" (click)="fileInputImage.click()">
<img src="assets/images/upload-image_80.png" style="width: 25%;">Upload
Image
</div>
<div class="pointer" (click)="fileInputVideo.click()">
<img src="assets/images/upload-video_80.png" style="width: 25%;">Upload
Video
</div>
</div>
<div class="modal-body text-center">
<span
style="visibility: hidden; position: absolute; overflow: hidden; width: 0px; height: 0px; border: none; margin: 0; padding: 0">
<input type="file" #fileInputImage accept='image/*'
(click)="isUpload='i'" (change)="preview(fileInputImage.files)"
ng2FileSelect [uploader]="uploader" />
</span> <span
style="visibility: hidden; position: absolute; overflow: hidden; width: 0px; height: 0px; border: none; margin: 0; padding: 0">
<input type="file" #fileInputVideo accept='video/*'
(click)="isUpload='v'" (change)="preview(fileInputVideo.files)"
ng2FileSelect [uploader]="uploader" />
</span>
</div>
<div class="modal-footer"
style="border-top: 0px; justify-content: center;">
<form [formGroup]="commentPopup" (ngSubmit)="onSubmit()">
<div class="form-group">
<textarea type="text" rows="5" maxlength="400"
formControlName="comment" class="form-control"
placeholder="Enter your comment here"
[ngClass]="{ 'is-invalid': submitted && f.comment.errors }"></textarea>
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-light"
(click)="modal.close('Close click');clearPreview();">Cancel</button>
<button (click)="uploader.uploadAll()" class="btn btn-primary"
[disabled]="!uploader.getNotUploadedItems().length">Post</button>
</div>
</form>
</div>
</ng-template>
TS file Code:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Headers } from '@angular/http';
constructor(private httpService: HttpClient, private modalService: NgbModal, private formBuilder: FormBuilder) {
this.isUpload = '';
}
openWindowCustomClass(content) {
this.modalService.open(content, { size: 'sm' });
}
validation() {
this.commentPopup = this.formBuilder.group({
comment: ['', Validators.required]
});
}
get f() { return this.commentPopup.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.commentPopup.invalid) {
return;
}
}
preview(files) {
if (files.length === 0)
return;
var mimeType = files[0].type;
if (mimeType.match(/image\/*/) == null && mimeType.match(/video\/*/) == null) {
this.message = "Only images / videos are supported.";
return;
}
var reader = new FileReader();
this.imageOrVideoPath = files;
reader.readAsDataURL(files[0]);
reader.onload = (_event) => {
this.imgOrVideoURL = reader.result;
}
}
clearPreview() {
this.validation();
this.imgOrVideoURL = null;
this.imageOrVideoPath = null;
this.comment = null;
this.isUpload='';
}
ngOnInit() {
this.fileUpload();
this.validation();
}
public uploader: FileUploader = new FileUploader({url: this.imageUploadUrl, headers:this.headers, method: 'POST' });
fileUpload() {
this.authHeaders.headers = [{ name: 'userId', value: '1234' },
{ name: 'deviceKey', value: '9999-8888-7777' }];
this.uploader.onBuildItemForm = (item, form) => {
form.append("content","TESTING");
form.append("author", "username");
};
this.uploader.onBeforeUploadItem = (item) => {
this.uploader.setOptions(this.authHeaders);
};
this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
console.log('ImageUpload:uploaded:', item, status, response);
if (status === 200) {
alert('File uploaded successfully');
this.uploadedResponse = response;
} else {
alert("something went wrong");
}
};
}