简体   繁体   中英

Map from HttpPostedFileBase to Byte[] with automapper

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:

  1. 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>(); 
  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM