通过POSTMAN发送时,HttpRequest.Files为空

时间:2017-07-13 00:35:32

标签: c# .net asp.net-web-api file-upload postman

我跟随此blog post使用C#Web API上传图片。

文章解释了如何使用ARC进行操作,并且工作正常。

但是当我尝试使用POSTMAN做同样的事情时,它就失败了。

这是我的请求快照。

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

在帖子中,您引荐的数据正在上传为“x-www-form-url-encoded”

您的邮差屏幕截图显示您将其上传为“表单数据”

此外,您添加了一个键“image01”,其中ARC示例似乎没有发送密钥。

如果您想使用表单数据上传文件,则需要a different approach

// POST api/files
public async Task<HttpResponseMessage> Post()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);

    string value;

    try
    {
        // Read the form data and return an async data.
        var result = await Request.Content.ReadAsMultipartAsync(provider);

        // This illustrates how to get the form data.
        foreach (var key in provider.FormData.AllKeys)
        {
            foreach (var val in provider.FormData.GetValues(key))
            {
                // return multiple value from FormData
                if (key == "value")
                    value = val;
            }
        }                       

        if (result.FileData.Any())
        {                    
            // This illustrates how to get the file names for uploaded files.
            foreach (var file in result.FileData)
            {
                FileInfo fileInfo = new FileInfo(file.LocalFileName);
                if (fileInfo.Exists)
                {
                   //do somthing with file
                }
            }
        }


        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, value);
        response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = files.Id }));
        return response;
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}

答案 1 :(得分:0)

哼!这太难道理了。除了您在工具中明确设置Content-Type标头外,您所做的一切都是正确的。你一定不能那样做。每当您在工具的form-data标签中的Body Content-Type附加文件时,邮递员会自动检测Content-Type并将其发送到您的帖子请求中。

Content-Type设置为&#34; multipart / form-data&#34;涉及一个复杂的概念,即将多个部分的边界设置为详细的here。因此,设置content-type标头会明确地混淆请求。设置边界的繁重工作是通过邮递员工具自动完成的,这就是为什么它不希望您在这种情况下明确设置Authorization。在我的系统上传图片文件时,请查看我是如何设置Authorization标题的:

enter image description here

如果您的网络服务器上没有任何身份验证,您甚至可能不需要此Headers标头。因此,您案例中有效的multipart/form-data标签应该是空的,即根本没有键值对。

注意:仅提供信息,图片文件的正确内容类型为export,即使您不需要在工具中明确设置它。