【发布时间】:2018-06-30 04:15:04
【问题描述】:
我想从 Angular 4 上传图片。在 WebApiController 中调用控制器方法并处理上传图片。请帮帮我!
我的组件 process.ts :
onUpload(file): void{
let fileList = FileList = file;
if(fileList.length > 0){
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('uploadFile',file, file.name);
this.catalogService.uploadFile(formData)
.subscribe(data => {
this.toastr.success('Ipload Image Successfully', 'Catalog Book');
})
}
}
我的服务.ts
uploadFile(form: any){
var headerOptions = new Headers({'Content-Type':'application/json'});
var requestOptions = new RequestOptions({method: RequestMethod.Post, headers: headerOptions});
return this.http.post('http://localhost:20952/api/UploadImage/',form,requestOptions).map(x=>x.json());
}
来自 Web API 的控制器处理
// POST: api/UploadImage
[HttpPost]
public IHttpActionResult GetCatalog(Guid id)
{
try
{
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];
string fileName = id + "jpg";
var filePath = HttpContext.Current.Server.MapPath("~/Data/" + fileName);
postedFile.SaveAs(filePath);
}
}
}
catch (Exception ex)
{
throw ex;
}
return Ok();
}
【问题讨论】:
-
现在有什么问题?
-
无法将“文件上传”传输到控制器 Web API
-
你能调用 api 吗?你没有将任何 Guid 传递给 api,而且路线也不同于你在 angular 中使用的路线
-
在api方法之前使用
[Route("api/UploadImage/"]并传递guid -
我无法想象将“文件上传”传输到 Web api 控制器的方式。
标签: c# angular asp.net-core-webapi