Search code examples
c#asp.netasp.net-mvcfilehttppostedfilebase

How to convert byte array to HttpPostedFileBase in C#?


I am using asp.net MVC web application. My requirement is to convert byte array to HttpPostedFileBase. I am creating byte array using filepath.

I have taken reference of this question
how to convert a byte[] to HttpPostedFileBase using c# (answer by https://stackoverflow.com/users/2678145/zerratar)

When I used that code I am getting exception while saving that converted file to server. Exception is method or operation is not implemented.

I thought I am getting error because, the content type and filename of converted file was returning null.

So I slightly changed the code like this.

public class HttpPostedFileForStl : HttpPostedFileBase
{
    private readonly byte[] fileBytes;

    public HttpPostedFileForStl(byte[] fileBytes, string fileName)
    {
        this.fileBytes = fileBytes;
        this.InputStream = new MemoryStream(fileBytes);
        this.FileName = fileName;
    }

    public override int ContentLength => fileBytes.Length;
    public override string FileName { get; }
    public override string ContentType { get; } = "application/octet-stream";
    public override Stream InputStream { get; }
}

I am passing byte array and filename to this class. Now I am getting appropriate filename and content type in converted file, but exception is still there. Can anyone help?


Solution

  •  public class HttpPostedFileBaseCustom : HttpPostedFileBase
        {
            private byte[] _Bytes;
            private String _ContentType;
            private String _FileName;
            private MemoryStream _Stream;
    
            public override Int32 ContentLength { get { return this._Bytes.Length; } }
            public override String ContentType { get { return this._ContentType; } }
            public override String FileName { get { return this._FileName; } }
    
            public override Stream InputStream
            {
                get
                {
                    if(this._Stream == null)
                    {
                        this._Stream = new MemoryStream(this._Bytes);
                    }
                    return this._Stream;
                }
            }
    
            public HttpPostedFileBaseCustom(byte[] contentData, String contentType, String fileName)
            {
                this._ContentType = contentType;
                this._FileName = fileName;
                this._Bytes = contentData ?? new byte[0];
            }
    
            public override void SaveAs(String filename)
            {
                System.IO.File.WriteAllBytes(filename, this._Bytes);
            } 
        }