无法从ASP.NET MVC中的操作返回图像流

时间:2015-09-17 16:28:01

标签: c# .net asp.net-mvc amazon-s3 stream

我有以下行动:

StaticImage

我有一个检索//E is StaticImage in this case //The returned entity is not disposed, it leaves that responsability to the controller //However, the response IS disposed, that's why I need to copy the stream public async Task<E> SelectAsync(params object[] keys) { using(GetObjectResponse response = await MakeGetObjectRequestAsync(keys.First().ToString())) { if(response == null) return default(E); E entity = CreateEntity(); entity.Key = response.Key; Stream entityStream = new MemoryStream(Convert.ToInt32(response.ResponseStream.Length)); await response.ResponseStream.CopyToAsync(entityStream); entity.Stream = entityStream; return entity; } } 的通用持久性策略(使用Amazon S3),如下所示:

response.ResponseStream

Length包含图片的内容:

enter image description here

它正好被复制到新流(参见0):

enter image description here

但是,我的控制器会返回10 +++ DO I = 1 TO SYSTSIN.0 Error running MYREXX, line 10: Bad arithmetic conversion 个字节:

enter image description here

1 个答案:

答案 0 :(得分:4)

如果查看第二张图片,则流的位置为197397。我的假设是当你将它传递给FileStreamResult的构造函数时,它不会复制它,因为位置在流的末尾。在将其传递给FileStreamResult的构造函数之前,请将位置设置回0:

StaticImage image = await _images.UseRepositoryAsync(repo => repo.ReadAsync(path));     
image.Stream.Position = 0;
return image != null ? new FileStreamResult(image.Stream, "image/jpeg") : (ActionResult)HttpNotFound();