Im trying to upload a picture 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 get an error on s : A lambda expression with a statement body cannot be converted to an expression tree.
So how should i write my CreateMap to get this to work?
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();
}
}
Usage:
Mapper.CreateMap<HttpPostedFileBase, byte[]>()
.ConvertUsing<HttpPostedFileBaseTypeConverter>();
Use ConstructUsing
and do it inline:
Mapper.CreateMap<HttpPostedFileBase, byte[]>()
.ConstructUsing(fb =>
{
MemoryStream target = new MemoryStream();
fb.InputStream.CopyTo(target);
return target.ToArray();
});
This is not the best way to read bytes from a file upload because IIS allocates the entire size of the uploading file when the uploading process starts. Then your mapper allocates another similar size of bytes (byte[] array is a new variable) and the overall memory usage is going to be file bytes * 2.
My advice is to read the posted file stream and to write it somewhere. You can do any post-upload processing after uploading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With