简体   繁体   English

如何使用Web API发布和接收文件

[英]How to post and receive a file with web api

I have a Api Post method that I want to be able to accept any file type and that looks like this: 我有一个Api Post方法,我希望它能够接受任何文件类型,如下所示:

[HttpPost]
    public async Task<IHttpActionResult> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

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

        if (provider.Contents.Count != 1)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest,
                "You must include exactly one file per request."));
        }

        var file = provider.Contents[0];
        var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
        var buffer = await file.ReadAsByteArrayAsync();
  }

This works in fiddler when I try to post an image to it. 当我尝试向其发布图像时,这在提琴手中起作用。 However, I'm writing a client library and I have a method that looks like this: 但是,我正在编写一个客户端库,并且有一个如下所示的方法:

        public string PostAttachment(byte[] data, Uri endpoint, string contentType)
    {
        var request = (HttpWebRequest)WebRequest.Create(endpoint);
        request.Method = "POST";
        request.ContentType = contentType;
        request.ContentLength = data.Length;

        var stream = request.GetRequestStream();
        stream.Write(data, 0, data.Length);
        stream.Close();

        var response = (HttpWebResponse) request.GetResponse();
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
           return reader.ReadToEnd();
        }            
    }

Whenever I try to post an image using this, I'm getting a UnsuportedMediaType error. 每当我尝试使用此方法发布图像时,都会收到UnsuportedMediaType错误。 I'm assuming it's because my image isn't Multi Part Content? 我假设是因为我的图像不是“多部分内容”? Is there an easy way to make my request of the correct type? 有没有一种简单的方法可以使我的请求类型正确?

If I have to change my web api post method, is there an easy way of doing that without writing files to the server and keeping it in memory? 如果我必须更改Web api post方法,是否有一种简单的方法可以在不将文件写入服务器并将其保存在内存中的情况下做到这一点?

The MultipartFormDataContent from the System.Net.Http namespace will allow you to post multipart form data. 来自System.Net.Http命名空间的MultipartFormDataContent将允许您发布多部分表单数据。

private async Task<string> PostAttachment(byte[] data, Uri url, string contentType)
{
  HttpContent content = new ByteArrayContent(data);

  content.Headers.ContentType = new MediaTypeHeaderValue(contentType); 

  using (var form = new MultipartFormDataContent())
  {
    form.Add(content);

    using(var client = new HttpClient())
    {
      var response = await client.PostAsync(url, form);
      return await response.Content.ReadAsStringAsync();
    }
  }
}

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

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