简体   繁体   English

使用AngularJS将文件发布到WebApi2-无法获取文件名或标题

[英]Posting files to WebApi2 using AngularJS - cannot get filename or headers

I am using AngularJS to allow someone to post a file to my web service which is using c# WebAPI 2. 我正在使用AngularJS允许某人将文件发布到使用c#WebAPI 2的Web服务中。

  self.AddDocument = function() { var f = document.getElementById('documentFile').files[0]; var r = new FileReader(); r.onloadend = function(e) { var data = e.target.result; console.log('AddDocument data' + data); var fd = new FormData(); fd.append('Attachment', f); $http.post('api/Document/' + $routeParams.changeId + '/AddDocument', fd, { method: 'POST', url: 'api/Document/' + $routeParams.changeId + '/AddDocument', data: fd, // I have tried application/x-www-form-urlencoded & application/octet-stream for the content type headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function(response) { console.log(response.data); }); }; r.readAsArrayBuffer(f); }; } 

This code works fine as far as I can tell in that I do get a HttpRequestMessage in my code coming through (see below), however there are no headers that are passed through - but I can see the content-disposition when I do ReadAsStringAsync 据我所知,这段代码可以正常工作(请参见下文),但我没有在代码中传递HttpRequestMessage,但是没有标题可以通过-但我在执行ReadAsStringAsync时可以看到内容处置

[HttpPost]
[Route("api/Document/{id}/AddDocument")]
public async Task<string> Add(HttpRequestMessage request)
{
    var doc = await request.Content.ReadAsByteArrayAsync();

    var values = Enumerable.Empty<string>();

    // this is always null
    var header = (request.Content.Headers.TryGetValues(name: "filename", values: out values))
        ? values.First()
        : null;

    // this will be the following
    /*
     * ------WebKitFormBoundaryQIUoHBmcWJTY9cJx
Content-Disposition: form-data; name="Attachment"; filename="IMG_8639.JPG"
Content-Type: image/jpeg
    */
    var str = await request.Content.ReadAsStringAsync();

    // code that will add the byte array, filename, etc to a database table...

    return "success";
}

How do I pull out the filename from an uploaded file? 如何从上传的文件中提取文件名?

From the first part of your code Code, what you doing is trying to mimic a http request object and Post that to to your Web API. 在代码的第一部分中,您正在尝试模仿http请求对象并将其发布到Web API。 Then inside you Web APi stack, Web API is trying to map the object you posted to the built in HttpRequestMessage object. 然后在Web APi堆栈内部,Web API尝试将您发布的对象映射到内置的HttpRequestMessage对象。

public async Task<string> Add(HttpRequestMessage request)

is equivalent to: 等效于:

public async Task<string> Add(FormData)

The HttpRequestMessage parameter is automatically bound so that you can get hold of request information in your controller method if you need to HttpRequestMessage参数是自动绑定的,因此,如果需要,您可以在控制器方法中获取请求信息

I guess what you should be doing is create a Model object in C# (WEb API) that maps directly to your FormData object, then the API stack will bind it correctly, you can pass the headers in the main $http.Post request and read them in Web Api controller. 我猜你应该做的是在C#(WEb API)中创建一个Model对象,该对象直接映射到FormData对象,然后API堆栈将其正确绑定,您可以在$ http.Post主请求中传递标头并读取它们在Web Api控制器中。

Hope this makes sense, I posted the whole code as I think the problem here is understanding of the concept. 希望这有意义,我发布了整个代码,因为我认为这里的问题是对概念的理解。 As an example check this Git Hub Sample , you can always adapt it to your needs 作为示例,请检查此Git Hub示例 ,您可以随时对其进行调整以适应您的需求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM