简体   繁体   中英

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?

 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);
        } 
    }

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