【问题标题】:Return list of images from web API从 Web API 返回图像列表
【发布时间】:2017-09-11 18:55:53
【问题描述】:

我正在使用 MVC 和 C# 开发 Web API,我尝试返回存储在文件夹中的图像列表以及它们在数据库中的路径,我正在尝试:

 public class Image {
    public int Id { get; set; }
    public string Path { get; set; }
    public int Item_Id { get; set; }
    public bool isMain { get; set; }
}

在图像控制器中我调用这个方法:

 [HttpGet]
    [ActionName("GetImageByItemId")]
    public HttpResponseMessage GetImages(int id)
    {
        try
        {
            using (var ctx = new ApplicationDbContext())
            {
                var entity = ctx.Images.Where(e => e.Item_Id == id).ToList();

                // ctx.Images.FirstOrDefault(e => e.Item_Id == id);
                if (entity != null)
                {
                    List<HttpResponseMessage> shapes = new List<HttpResponseMessage>();
                    HttpResponseMessage response = new HttpResponseMessage();
                    for (int i = 0; i < entity.Count; i++)
                    { 

                    String filePath = HostingEnvironment.MapPath("~/Images/" + entity[i].Path + ".jpg");
                    FileStream fileStream = new FileStream(filePath, FileMode.Open);
                    response.Content = new StreamContent(fileStream); // this file stream will be closed by lower layers of web api for you once the response is completed.
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                    shapes.Add(response);
                    }
                     // return response;
                    // return Request.CreateResponse(HttpStatusCode.OK, shapes);
                    return ControllerContext.Request
        .CreateResponse(HttpStatusCode.OK, new {shapes});
                }
                else
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "The Images With ID" + id.ToString() + " Not Found");
                }
            }
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }

如果我使用

return response;

return  shapes[1];

返回一个图像是可行的,但我需要它返回一个图像列表,该怎么做?

【问题讨论】:

标签: c# entity-framework asp.net-web-api


【解决方案1】:

一个 HTTP 响应可以包含零或一 (1) 个内容。没有了。

合乎逻辑的解决方案

如果您想提供多个文件,则需要根据需要发出尽可能多的请求。

首先,创建一个 MVC 操作,该操作将返回可用于给定实体 ID 的文件列表。

然后,进行 MVC 操作,将实体 id文件 id 作为参数。

在客户端,首先调用第一个方法。然后根据要下载的文件多次调用第二个。

打包解决方案

您还可以使用System.IO.Packagingknown library 将多个文件打包成一个文件(zip、tar、7zip...)。

外星人解决方案

您也可以尝试在服务器端和客户端实现MIME 规范。警告:当前的网络浏览器没有实现它。这显然是非标准,因此不推荐This article 似乎解决了这项技术。

【讨论】:

  • 不,我需要在另一个应用程序中显示它们。那么还有其他方法可以做到这一点并返回图像列表吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多