Vignesh VS
Vignesh VS

Reputation: 939

How to post a file to a variable (with type 'HttpPostedFileBase' ) in controller

I have a variable with HttpPostedFileBase as type in my model. The model is given below:

    public class MailModel
    {
        public int mail_id { get; set; }
        public string From { get; set; }
        public string To { get; set; }
        public string subject { get; set; }
        public string Content { get; set; }
        public HttpPostedFileBase file { get; set; }

    }

Now I want to assign a value to the variable file from my local file path. How can I assign a value to file in the corresponding controller?

    public class MailController : Controller
    {
       MailModel mm = new MailModel();
       mm.file = ?            //Can I add a filepath?
    }

Thank you!

Upvotes: 4

Views: 5074

Answers (1)

Vignesh VS
Vignesh VS

Reputation: 939

Finally, I got the solution. I have converted the file path into bytes using the following code:

    byte[] bytes = System.IO.File.ReadAllBytes(FilePath);

I created a derived class for HttpPostedFileBase in MailModel.

    public class MemoryPostedFile : HttpPostedFileBase
    {
        private readonly byte[] FileBytes;
        private string FilePath;

        public MemoryPostedFile(byte[] fileBytes, string path, string fileName = null)
        {
            this.FilePath = path;
            this.FileBytes = fileBytes;
            this._FileName = fileName;
            this._Stream = new MemoryStream(fileBytes);
        }

        public override int ContentLength { get { return FileBytes.Length; } }
        public override String FileName { get { return _FileName; } }
        private String _FileName;
        public override Stream InputStream
        {
            get
            {
                if (_Stream == null)
                {
                    _Stream = new FileStream(_FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                }
                return _Stream;
            }
        }
        private Stream _Stream;
        public override void SaveAs(string filename)
        {
            System.IO.File.WriteAllBytes(filename, System.IO.File.ReadAllBytes(FilePath)); 
        }
    }

Then I call it from MailController using the following code:

public class MailController: Controller
{
   byte[] bytes = System.IO.File.ReadAllBytes(FilePath);
   MailModel model= new MailModel();
   model.file = (HttpPostedFileBase)new MemoryPostedFile(bytes, FilePath, filename);
}

Now I can assign a value to the variable "file" (with type HttpPostedFileBase)

Upvotes: 3

Related Questions