簡體   English   中英

使用AngularJS將文件發布到WebApi2-無法獲取文件名或標題

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

我正在使用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); }; } 

據我所知,這段代碼可以正常工作(請參見下文),但我沒有在代碼中傳遞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";
}

如何從上傳的文件中提取文件名?

在代碼的第一部分中,您正在嘗試模仿http請求對象並將其發布到Web API。 然后在Web APi堆棧內部,Web API嘗試將您發布的對象映射到內置的HttpRequestMessage對象。

public async Task<string> Add(HttpRequestMessage request)

等效於:

public async Task<string> Add(FormData)

HttpRequestMessage參數是自動綁定的,因此,如果需要,您可以在控制器方法中獲取請求信息

我猜你應該做的是在C#(WEb API)中創建一個Model對象,該對象直接映射到FormData對象,然后API堆棧將其正確綁定,您可以在$ http.Post主請求中傳遞標頭並讀取它們在Web Api控制器中。

希望這有意義,我發布了整個代碼,因為我認為這里的問題是對概念的理解。 作為示例,請檢查此Git Hub示例 ,您可以隨時對其進行調整以適應您的需求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM