[英]Using CryptoStream with StreamContent c#
I would like to to read an image from file or blob storage and base64 encode it as a stream and then pass that stream to StreamContent.我想从文件或 blob 存储中读取图像,然后 base64 将其编码为流,然后将该流传递给 StreamContent。 The following code times out:
以下代码超时:
[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;
}
I am able to get the following code to work without keeping the file as a stream and read it all into memory but I would like to avoid that.我能够在不将文件保留为流并将其全部读入内存的情况下使以下代码工作,但我想避免这种情况。
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;
}
}
The problem here is you're passing CryptoStreamMode.Write
to the constructor of CryptoStream
whereas you should be passing CryptoStreamMode.Read
because the CryptoStream
is going to be read as the HttpResponseMessage
is returned.这里的问题是要传递
CryptoStreamMode.Write
到的构造CryptoStream
,而你应该通过CryptoStreamMode.Read
因为CryptoStream
将被读成HttpResponseMessage
返回。
For more details about this, see Figolu's great explanation about the various usages of CryptoStream
in this answer .有关这方面的更多详细信息,请参阅 Figolu 在此答案中对
CryptoStream
的各种用法的精彩解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.