【问题标题】:Return image url as result of web api 2 query返回图像 url 作为 web api 2 查询的结果
【发布时间】:2015-08-05 07:08:54
【问题描述】:

编辑: 我已经更新了一个控制器来获取流资源,但是它仍然无法正常工作

public class ResourcesController : Controller
{
    public string Directory = @"D:\Desktop\MusicDatabase\Image\";

    [HttpGet]
    [Route("Image/{type}/{id}")]
    public HttpResponseMessage Image(string type, string id)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
        var url = Path.Combine(Directory, type, id + ".jpg");
        byte[] fileData = System.IO.File.ReadAllBytes(url);
        MemoryStream ms = new MemoryStream(fileData);
        httpResponseMessage.Content = new StreamContent(ms);
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
        return httpResponseMessage;
    }     
}

它返回一个字符串,而不是资源文件

当我调试时,“url”变量是

"D:\\Desktop\\MusicDatabase\\Image\\song\\2.jpg"

旧:

我有 2 个项目:1 个用于服务器的 web api2,1 个用于客户端的 WP8 应用程序。

服务器包含我链接到外部文件资源的数据库

e.x 一个带有 IMAGE 列的 Song 表,我将这张图片存储在我的桌面中

public partial class Song
{    
    public int Id { get; set; }        
    public string NAME { get; set; }

    private string _IMAGE;
    public string IMAGE 
    { 
        get
        {
            return Helper.Helper.ConcatDirectory(_IMAGE);
        }
        set
        {
            _IMAGE = value;
        }
    }

在我的数据库中,我仅通过其索引存储“IMAGE”列(如“Song\1.jpg”),然后当我有一些查询要切断时,我通过这个返回完整的 URL

public class Helper
{
    public static string Directory = "D:\\Desktop\\MusicDatabase\\";
    public static string ConcatDirectory(string input)
    {
        return string.Concat(Directory, input);
    }
}

当我在网络浏览器中尝试查询时,此 URL 将返回存储在我的 PC 中的文件

但我的 WP8 应用无法显示此图像(使用模拟器调试)。 虽然我不想将此资源存储在我的项目中,但无论如何要在此处返回这些图像吗? (以后任何不同的文件类型,如歌曲、视频...)

【问题讨论】:

  • IMAGE 是一个字符串,包含图像的路径。您不能只将其发送到手机并显示图像。您需要读取图像文件的内容并在响应中发送该二进制数据。
  • 请看一下这个解决方案:stackoverflow.com/questions/13001588/…。这样您就可以从手机中读取图像了。
  • @ParthShah :我已经更新了问题,但仍然无法正常工作,我是服务器应用程序的新手

标签: c# windows-phone-8 asp.net-web-api2


【解决方案1】:

请更换

httpResponseMessage.Content = new StreamContent(ms);

httpResponseMessage.Content = new ByteArrayContent(ms);

编辑:

我真的认为您应该尝试了解其他 SO 用户的以下建议:

1) 在 ASP.NET WebAPI 中处理静态图像:https://stackoverflow.com/a/12559507/2310818

【讨论】:

    猜你喜欢
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多