[英]Angular Upload File and Additional Data ASP WebAPI
我正在尝试将包含一些文本字段和文件的表单上传到我的WebAPI。 目前,我总是收到415错误(ASP控制器中的断点未命中)。 我的代码看起来像这样:
角度服务
// 'Upload' is from ng-file-upload
function applicationService(settings, $http, Upload) {
var createCustomApplication = function(application) {
var url = settings.baseUrl + '/api/applications/custom';
var data = new FormData();
angular.forEach(application, function (value, key) {
data.append(key, value);
});
return Upload.upload({
url: url,
data: data,
method: 'POST'
});
};
return {
createCustomApplication: createCustomApplication
}
}
WebAPI控制器
[ResponseType(typeof(ApplicationModel))]
[HttpPost, Route("api/applications/custom")]
public IHttpActionResult CreateCustomApplication([FromBody]ApplicationModel application)
{
var file = HttpContext.Current.Request.Files[0];
return Ok();
}
如果要包含带有文件的表单作为操作的参数,则必须添加自定义媒体格式化程序。 幸运的是,已经有人为此创建了一个Nuget包 。 配置很容易。 安装软件包,并在您的WebApiConfig文件中添加一行。
该软件包允许您使用HttpFile
,该对象直接作为参数或在模型内部捕获文件。 从文档 :
[HttpPost]
public void PostFileBindRawFormData(MultipartDataMediaFormatter.Infrastructure.FormData formData)
{
HttpFile file;
formData.TryGetValue(<key>, out file);
}
要么
public class PersonModel
{
public string FirstName {get; set;}
public string LastName {get; set;}
public DateTime? BirthDate {get; set;}
public HttpFile AvatarImage {get; set;}
public List<HttpFile> Attachments {get; set;}
public List<PersonModel> ConnectedPersons {get; set;}
}
//api controller example
[HttpPost]
public void PostPerson(PersonModel model)
{
//do something with the model
}
您的代码看起来与我使用的代码非常相似。 也许问题在于multipart / form-data标头值。 我没有足够的经验来讲述您的实现中有什么问题,但是也许尝试这种替代的异步等待方法。
[Route("api/applications/custom")]
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
MultipartMemoryStreamProvider memoryStreamProvider;
try
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
memoryStreamProvider = await Request.Content.ReadAsMultipartAsync();
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, string.Format("An error has occured while uploading your file. Error details: '{0}'", e.Message));
}
// do something with your file...
return Request.CreateResponse(HttpStatusCode.OK);
}
这是我的JS代码。 我还使用Promise,而不是从Upload函数返回的内容(如果有的话)。
$scope.submit = function() {
if ($scope.form.file.$valid && $scope.file) {
$scope.upload($scope.file);
}
};
$scope.upload = function(file) {
Upload.upload({
url: 'api/applications/custom',
data: { file: file }
}).then(function(response) {
// report the success to the user
}, function(response) {
// report the error to the user
}, function(evt) {
// report the progress of the upload to the user
$scope.uploadProgress = evt.loaded / evt.total;
});
};
我将以下文章用作解决方案的基础: http : //monox.mono-software.com/blog/post/Mono/233/Async-upload-using-angular-file-upload-directive-and-net-的WebAPI服务/
我有同样的问题。 您应该在POST请求中添加内容类型。
headers: {
'Content-Type': undefined
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.