Angular Ng-File-Upload url找不到MVC ApiController方法

时间:2016-03-31 14:49:54

标签: angularjs asp.net-mvc asp.net-mvc-routing asp.net-web-api-routing

我正在尝试使用ng-file-upload上传文件并将blob保存到数据库,如上一个问题Ng-File-Upload to Save PDF Blob to Database

我相信我有“正确”的代码来完成任务,但现在的问题是我无法获得代码来“击中”ApiController中的方法。如果我将该方法放在常规异步控制器中,它会找到它(但是我不能使用所需的一半代码,因为它不起作用,除非它在一个继承自ApiController的控制器中),但它不会在ApiController中找到相同的方法。我错过了什么?

以下是角度控制器代码:

angular.module('myModule').controller('DocumentCtrl', function ($scope, $interval, $window, $filter, $q, $timeout, Upload, $http) {
$scope.uploadPic = function (file) {
    file.upload = Upload.upload({
        url: '/SSQV4/SSQV5/Document/UploadEMRDocument',
        method: 'POST',
        data: { file: file }
    })
}

}) 这是MVC控制器代码:

public class DocumentController : ApiController
{

    public async Task<IHttpActionResult> UploadEMRDocument()
    {

        try
        {
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            var f = provider.Contents.First(); // assumes that the file is the only data

            if (f != null)
            {
                var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
                filename = Path.GetFileName(filename);
                var buffer = await f.ReadAsByteArrayAsync();

                //buffer now contains the file content,
                //and filename has the original filename that was uploaded

                //do some processing with it (e.g. save to database)
            }
            else
            {
                return BadRequest("Attachment failed to upload");
            }
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }

        return Ok();

    }
}

我假设这是某种路由问题,但我不确定。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

上传正在使用Http POST发送文件,但是,您没有指定您的操作方法应该监听POST。只需添加HttpPost属性:

[HttpPost]
public async Task<IHttpActionResult> UploadEMRDocument()

答案 1 :(得分:0)

我需要将网址更改为

url: '/SSQV4/SSQV5/api/Document/UploadEMRDocument'

现在它命中了它。感谢您的帮助Nava-Prev.Queti!