45

问题

  1. 将图像 POST/GET 到我的服务有哪些不同的方法?我想我可以在 JSON 中使用 Base-64 文本,也可以保持原生二进制。我的理解是,通过将图像转换为文本,包大小会显着增加。

  2. 如果我发送图像(从 Web 表单、本机客户端、其他服务),我应该添加图像控制器/处理程序还是使用格式化程序?这甚至是一个非此即彼的问题吗?

我研究并发现了许多相互竞争的例子,但我不确定我应该朝着哪个方向前进。

是否有网站/博客文章列出了这方面的利弊?

4

2 回答 2

29

我做了一些研究,你可以在这里看到我提出的实现:http: //jamessdixon.wordpress.com/2013/10/01/handling-images-in-webapi/

于 2013-10-01T09:54:06.910 回答
27

为了保存起见 - 以下是 Jamie 博客所说的概要:

使用控制器:

得到:

public HttpResponseMessage Get(int id)
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");
    FileStream fileStream = new FileStream(filePath, FileMode.Open);
    Image image = Image.FromStream(fileStream);
    MemoryStream memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Jpeg);
    result.Content = new ByteArrayContent(memoryStream.ToArray());
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

    return result;
}

删除:

public void Delete(int id)
{
    String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");
    File.Delete(filePath);
}

邮政:

public HttpResponseMessage Post()
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    if (Request.Content.IsMimeMultipartContent())
    {
        //For larger files, this might need to be added:
        //Request.Content.LoadIntoBufferAsync().Wait();
        Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(
                new MultipartMemoryStreamProvider()).ContinueWith((task) =>
        {
            MultipartMemoryStreamProvider provider = task.Result;
            foreach (HttpContent content in provider.Contents)
            {
                Stream stream = content.ReadAsStreamAsync().Result;
                Image image = Image.FromStream(stream);
                var testName = content.Headers.ContentDisposition.Name;
                String filePath = HostingEnvironment.MapPath("~/Images/");
                //Note that the ID is pushed to the request header,
                //not the content header:
                String[] headerValues = (String[])Request.Headers.GetValues("UniqueId");
                String fileName = headerValues[0] + ".jpg";
                String fullPath = Path.Combine(filePath, fileName);
                image.Save(fullPath);
            }
        });
        return result;
    }
    else
    {
        throw new HttpResponseException(Request.CreateResponse(
                HttpStatusCode.NotAcceptable,
                "This request is not properly formatted"));
    } 
}
于 2016-09-13T07:03:01.387 回答