将CryptoStream与StreamContent C#一起使用



我想从文件或blob存储中读取图像,然后base64将其编码为流,然后将该流传递到streamContent。以下代码时间:

[HttpGet, Route("{id}", Name = "GetImage")]
public HttpResponseMessage GetImage([FromUri] ImageRequest request)
{
   var filePath = HostingEnvironment.MapPath("~/Areas/API/Images/Mr-Bean-Drivers-License.jpg");
   HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
   var stream = new FileStream(filePath, FileMode.Open);
   var cryptoStream = new CryptoStream(stream, new ToBase64Transform(), CryptoStreamMode.Write);
   result.Content = new StreamContent(cryptoStream);
   result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
   return result;
}

我能够在不保留文件作为流并将其全部读取为存储器的情况下获得以下代码工作,但我想避免。

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
    using (var image = Image.FromStream(fileStream))
    {
        var memoryStream = new MemoryStream();
        image.Save(memoryStream, image.RawFormat);
        byte[] imageBytes = memoryStream.ToArray();
        var base64String = Convert.ToBase64String(imageBytes);
        result.Content = new StringContent(base64String);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
        return result;
    }
}

这里的问题是,您是将CryptoStreamMode.Write传递给CryptoStream的构造函数,而您应该通过CryptoStreamMode.Read,因为CryptoStream将在返回HttpResponseMessage时被读取。

有关此的更多详细信息,请参见Figolu在此答案中对CryptoStream的各种用法的很好解释。

相关内容

  • 没有找到相关文章

最新更新