I have looked at several SO question and answer but not able to solve my problem. My code is like below:
HTML
<input type="file" id="file" accept="image/*" name="File" (change)="handleFileInput($event.target.files)">
<button type="button" mat-raised-button color="primary" (click)="uploadFileToActivity()">Upload</button>
Component
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
this._dishAddService.postFile(this.fileToUpload).subscribe(data => {
}, error => {
console.log(error);
});
}
Service
postFile(fileToUpload: File): Observable<boolean> {
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Content-Type', 'multipart/form-data');
let options = new RequestOptions({ headers: headers, method: 'post' });
return this.http.post(this.httpRequestUrl + 'api/dish/UploadDishImage', formData, options)
.map(
(response => response.json()))
.catch(CommonFunctionService.handleError);
}
API
[HttpPost]
[ActionName("UploadDishImage")]
public HttpResponseMessage UploadJsonFile()
{
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
}
return response;
}
When request hit the API, files count is 0. I have spent whole two days to figure out what is going wrong but also not able to figure out wrong. I don't think there is wrong with the code because for some other it is working. I took code from different SO accepted answer. Could anybody help me figure out what might have gone wrong?