如何使用Web API发布和接收文件 [英] How to post and receive a file with web api

查看:219
本文介绍了如何使用Web API发布和接收文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Api Post方法,我希望它能够接受任何文件类型,如下所示:

I have a Api Post method that I want to be able to accept any file type and that looks like this:

[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();
        }            
    }

每当我尝试使用此方法发布图像时,都会收到UnsuportedMediaType错误.我假设是因为我的图像不是多部分内容"?有没有一种简单的方法可以使我的请求类型正确?

Whenever I try to post an image using this, I'm getting a UnsuportedMediaType error. 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?

如果我必须更改Web api post方法,是否有一种简单的方法而无需将文件写入服务器并保存在内存中呢?

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?

推荐答案

System.Net.Http名称空间中的MultipartFormDataContent将允许您发布多部分表单数据.

The MultipartFormDataContent from the System.Net.Http namespace will allow you to post multipart form data.

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();
    }
  }
}

这篇关于如何使用Web API发布和接收文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆