Angular 上传文件和附加数据 ASP WebAPI

Angular Upload File and Additional Data ASP WebAPI

我正在尝试将包含一些文本字段和文件的表单上传到我的 WebAPI。目前我总是收到 415 错误(ASP 控制器中的断点未命中)。我的代码如下所示:

Angular 服务

// '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();
}

我遇到了同样的问题。 您应该在 POST 请求中添加内容类型。

headers: {
     'Content-Type': undefined
},

您的代码看起来与我使用的非常相似。也许问题与 multipart/form-data header 值有关。我没有足够的经验来说明您的实现有什么问题,但也许可以尝试这种替代的异步等待方法。

[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 代码。我还使用 promises 而不是从上传函数返回的内容(如果有的话)。

$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-service/

如果您想要包含一个带有文件的表单作为操作的参数,则有必要添加自定义媒体格式化程序。 Fortunately someone already created a Nuget-package for this。配置很容易。安装包并在您的 WebApiConfig 文件中添加一行。

此包允许您使用 HttpFile-object,它可以直接将您的文件捕获为参数或在模型中捕获。 From the docs:

[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
}