I, am trying to upload the file using angular 5 in asp.net core 2.0.
Here is my server side code.
public class QuestionViewModel
{
public Guid QuestionId { get; set; }
public string QuestionText { get; set; }
public DateTime CreateDate { get; set; }
public string PictureUrl { get; set; }
public FormFile FileUpload { get; set; }
}
Here us the controller method.
[HttpPost]
[AllowAnonymous]
public JsonResult QuestionPhotoPost([FromBody] QuestionViewModel model)
{
GenericResponseObject<List<QuestionViewModel>> genericResponseObject = new GenericResponseObject<List<QuestionViewModel>>();
genericResponseObject.IsSuccess = false;
genericResponseObject.Message = ConstaintStingValue.TagConnectionFailed;
List<QuestionViewModel> questionViewModel = new List<QuestionViewModel>();
return Json(genericResponseObject);
}
Type Script class
export class Data {
QuestionText: string = "";
FileUpload: File;
}
Here is the http call. The call is invoke to the controller method .
public QuestionPostHttpCall(_loginVM: QuestionVmData): Observable<QuestionPhotoViewModel> {
console.log(_loginVM)
const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this._httpClientModule.post<QuestionPhotoViewModel>(this.questionPhoto, _loginVM, { headers});
}
Here is the data before sending to the server.
But in the controller the file is value in null.
The other property are binded to the controller parameter only file is not binded.
Can anyone please tell me where I, am doing wrong. references - ASP.NET Core 2.0 and Angular 4.3 File Upload with progress
You need to send file like multipart/form-data.
upload(file: File, questionText: string): Observable<FileResponseModel> {
const url: string = Urls.uploadFiles();
const formData: FormData = new FormData();
formData.append('attachment', file, file.name);
formData.append('questionText', questionText);
const options = {
headers: new HttpHeaders().set('enctype', 'multipart/form-data')
};
return this.httpService.post(url, formData, options);
}
Frontend
private headers: { "Content-Type": "multipart/form-data", boundary: "enterhereurboundary" };
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('usersFile', file);
$http.post(uploadUrl, fd, {
headers: this.headers
})
.success(function(){
})
.error(function(){
});
}
Backend
// POST: api/...
[HttpPost]
public async Task<ActionResult<string>> UploadUsersAsync(IFormFile usersFile)
{
// do something here...
}
Also, notice that the name of the file u send in the frontend has to be the same as the IFormFile variable name you use in the backend...
Related links
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.