Map from HttpPostedFileBase to Byte [] with automaton
I am trying to upload an image and use automapper to convert it from HttpPostedFileBase to Byte []. This is my CreateMap:
Mapper.CreateMap<HttpPostedFileBase, Byte[]>()
.ForMember(d => d, opt => opt.MapFrom(s =>
{
MemoryStream target = new MemoryStream();
s.InputStream.CopyTo(target);
return target.ToArray();
}));
I am getting the error s: lambda expression with statement body cannot be converted to an expression tree.
So how do I write my CreateMap to get this to work?
source to share
There are at least two ways to do this:
-
Use a custom type converter :
public class HttpPostedFileBaseTypeConverter : ITypeConverter<HttpPostedFileBase, byte[]> { public byte[] Convert(ResolutionContext ctx) { var fileBase = (HttpPostedFileBase)ctx.SourceValue; MemoryStream target = new MemoryStream(); fileBase.InputStream.CopyTo(target); return target.ToArray(); } }
Using:
Mapper.CreateMap<HttpPostedFileBase, byte[]>() .ConvertUsing<HttpPostedFileBaseTypeConverter>();
-
Use
ConstructUsing
and make it inline:Mapper.CreateMap<HttpPostedFileBase, byte[]>() .ConstructUsing(fb => { MemoryStream target = new MemoryStream(); fb.InputStream.CopyTo(target); return target.ToArray(); });
source to share
This is not the best way to read the bytes from the file download because IIS allocates the entire download size when the download process starts. Then your mapper allocates another similar byte size (byte [] is a new variable), and the total memory usage will be file * 2 bytes.
My advice is to read the posted file stream and write it somewhere. Once downloaded, you can perform any subsequent download.
source to share