Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 232
TobiasW Avatar asked Aug 11 '14 11:08

TobiasW


2 Answers

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();
    });
    
like image 96
Andrew Whitaker Avatar answered Oct 18 '22 22:10

Andrew Whitaker


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.

like image 28
Omer Faruk Zorlu Avatar answered Oct 18 '22 22:10

Omer Faruk Zorlu