Я изо всех сил пытался загрузить файлы из Angular6 в Asp.Net Core 2.1 Web API:
Ссылка, по которой я следую, чтобы сделать это, такова: http://www.talkingdotnet.com/upload-file-angular-5-asp-net-core-2-1-web-api/
Яне делаю точных вещей, так как у меня есть отдельный файл службы ts, из которого я вызываю post api, он выглядит примерно так:
Мой файл user.service.ts
PostImage(caption: string, fileToUpload: File) {
const formData: FormData = new FormData();
formData.append(fileToUpload.name, fileToUpload);
// formData.append('ImageCaption', caption);
const url = (`${this.baseURL + this.SchoolApiRoot}/UploadImage`);
return this.http.post(url, formData);
}
МойФайл Component.ts:
upload() {
let file = '';
let urltype = '';
let filename = '';
// let b: boolean;
for (let i = 0 ; i < this.urls.length ; i++) {
file = this.selectedFiles[i];
urltype = this.urltype[i];
filename = file[0];
const lfilename = filename['name'];
// const file = this.selectedFiles.item(0);
// console.log(file);
const k = uuid() + '.' + lfilename.substr((lfilename.lastIndexOf('.') + 1));
this.userservice.PostImage('test', this.selectedFiles[i]).subscribe(data => {
console.log(data);
});
// b = this.uploadService.uploadfile(filename, k);
// console.log('b: ' + b);
}
// return b;
}
Мой файл Asp.Net Core WebAPI:
[HttpPost]
//[EnableCors("AllowAnyOrigin")]
//[Authorize]
public async Task<Object> UploadImage()
{
try
{
var file = Request.Form.Files[0];
// string folderName = "Upload";
// string webRootPath = _hostingEnvironment.WebRootPath;
// string newPath = Path.Combine(webRootPath, folderName);
// if (!Directory.Exists(newPath))
// {
// Directory.CreateDirectory(newPath);
// }
// if (file.Length > 0)
// {
// string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
// string fullPath = Path.Combine(newPath, fileName);
// using (var stream = new FileStream(fullPath, FileMode.Create))
// {
// file.CopyTo(stream);
// }
// }
return Json("Upload Successful.");
}
catch (System.Exception ex)
{
return Json("Upload Failed: " + ex.Message);
}
}
Да, я прокомментировал весь другой код в контроллере Asp.Net для проверки.
В ошибке четко указано, что файл, который я отправляю из приложения Angular, не получается с конца WebAPI.
Что-то не так в моем подходе?или какая-либо ошибка, которую мне не удалось обнаружить?