Angular Upload File and Additional Data ASP WebAPI

本文关键字:Data ASP WebAPI Additional and Upload File Angular | 更新日期: 2023-09-27 18:35:56

我正在尝试将带有一些文本字段和文件的表单上传到我的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
  }
}

网络接口控制器

[ResponseType(typeof(ApplicationModel))]
[HttpPost, Route("api/applications/custom")]
public IHttpActionResult CreateCustomApplication([FromBody]ApplicationModel application)
{
   var file = HttpContext.Current.Request.Files[0];
   return Ok();
}

Angular Upload File and Additional Data ASP WebAPI

如果要

将带有文件作为参数的表单包含在操作中,则必须添加自定义媒体格式化程序。幸运的是,有人已经为此创建了一个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
}

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

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

你的代码看起来和我用的非常相似。也许问题与多部分/表单数据标头值有关。我没有足够的经验说出您的实现中出了什么问题,但也许可以尝试这种替代异步等待方法。

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