需要显示从WebApi调用中检索到的图像。

30 浏览
0 Comments

需要显示从WebApi调用中检索到的图像。

出于安全原因,我需要以正常HTML的方式显示一张图片,但我不能提供图片的正常url。相反,我需要从WebApi服务中检索图片。我找到了这个链接: https://stackoverflow.com/a/24985886/1481314,我已经查看了答案中提供的链接,但有些东西不起作用。我只能得到一个缺失图片的占位符。

这是我的客户端代码:

angular.element('#' + imageType + '_' + itemID).html('')

这是我的WebApi控制器方法:

[HttpGet]

[Route("api/filemanagermaindata/getFile")]

public HttpResponseMessage GetFile(string systemName, int fileID)

{

var customerData = ValidateUser(systemName, 0);

var response = this.fileMover.GetFileDataHttpResponse(customerData.OrganizationID, fileID);

return response;

}

这是获取并返回图片的类方法:

var response = new HttpResponseMessage();

try

{

FileManagerItem item = this.dataService.GetFileByID(fileID);

var fullPath = this.rootLocation + Path.Combine( item.PhysicalPath, item.Name);

if (!File.Exists(fullPath))

{

throw new Exception("无法找到请求的文件");

}

var fileType = Path.GetExtension(item.Name).Replace(".", string.Empty);

if (ApplicationSettings.Instance.ImageFileExtensions.Contains(fileType))

{

fileType = string.Format("image/{0}", fileType);

}

using (FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read))

{

response = new HttpResponseMessage { Content = new StreamContent(fileStream) };

response.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType);

response.Content.Headers.ContentLength = fileStream.Length;

};

return response;

}

0
0 Comments

需要显示从WebApi调用中检索到的图像。出现这个问题的原因是使用{}块会在数据加载之前关闭FileStream。

解决方法是将FileStream的关闭移到数据加载之后。下面是修改后的代码:

using (MemoryStream stream = new MemoryStream())
{
    using (var httpClient = new HttpClient())
    {
        using (var response = await httpClient.GetAsync(url))
        {
            await response.Content.CopyToAsync(stream);
        }
    }
    stream.Position = 0;
    var image = Image.FromStream(stream);
    // 在这里显示图像
}

这样做可以确保在数据加载完成后再关闭FileStream,从而成功显示从WebApi调用中检索到的图像。

0