This is the request payload I get.
fileChange(event) {
debugger;
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 httpHeaders = new HttpHeaders()
.set('Authorization', 'Bearer ' + this.access_token)
.set('Content-Type', 'multipart/form-data');
let endpoint = "Online/UploadImage";
this.httpClient
.post(this.host + endpoint, formData, { headers: httpHeaders, responseType: 'json' })
.subscribe(data => {
// do something, if upload success
console.log(data);
}, error => {
console.log(error);
});
}
}
Above is my ts file in Angular
<input type="file" (change)="httpService.fileChange($event)" name="uploadFile"/>
Above is my HTML file
[HttpPost]
[Route("api/Online/UploadImage")]
public string UploadFile()
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(
HttpContext.Current.Server.MapPath("~/Resources/Images/"),
fileName
);
file.SaveAs(path);
}
return file != null ? "~/Resources/Images/" + file.FileName : null;
}
And here is my web API in ASP.Net.
I'm really stuck as to why the current request is returning null? I can see that the front-end seems to be working okay.. But really I'm quite confused as to how to upload a file to my server. Please recommend what I should do to achieve that.