Вот код для вызова на событие, такое как Загрузить
const formData: FormData = new FormData();
const params = Object.assign({}, {
Id: 01010,
FileName: file.name,
FilePath: '', // this will be in Web API, so no need to pass from UI.
CreatedBy: 'test-user'
});
formData.append('uploadFile', file, params.FileName);
formData.append('myObjectClass', JSON.stringify(params));
this.myService.uploadAttachments(formData).subscribe (resp => {
// your code here
},
(error) => {
console.log('POST ERROR in method uploadAttachments: ' + error.error);
}
);
Ваш сервис.TS
uploadAttachments(formData: any): any {
const headers = new HttpHeaders();
/** In Angular 5, including the header Content-Type can invalidate your request */
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
return this.http.post(this.baseURL +
'Controller/UpdateInsertAttachments', formData,
{headers: headers});
}
В веб-API:
[HttpPost]
[ResponseType(typeof(YourClass))] // optional
public IHttpActionResult UpdateInsertAttachments()
{
try
{
CustomerAttachment cust= new CustomerAttachment();
HttpPostedFile postedFile = null;
var httpRequest = HttpContext.Current.Request;
var filePath = string.Empty;
if (httpRequest.Files.Count == 1)
{
postedFile = httpRequest.Files[0];
var filePath = HttpContext.Current.Server.MapPath("../" +
postedFile.FileName);
// var path = ConfigurationManager.AppSettings["FilePath"];
postedFile.SaveAs(filePath);
}
var json = httpRequest.Form["myObjectClass"];
cust = JsonConvert.DeserializeObject<CustomerAttachment>(json);
cust .FilePath = filePath;
return Ok(0);
}
catch (Exception ex)
{
return new HttpActionResult(HttpStatusCode.InternalServerError, ex.Message);
}
}