我的模型中有一个类型为HttpPostedFileBase的变量。模型如下:

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

    }

现在,我想从本地文件路径为变量file赋值。如何在相应的控制器中为file赋值?
    public class MailController : Controller
    {
       MailModel mm = new MailModel();
       mm.file = ?            //Can I add a filepath?
    }

谢谢您!

最佳答案

最后,我找到了解决办法。我已使用以下代码将文件路径转换为字节:

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

我在HttpPostedFileBase中为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));
        }
    }

然后我使用以下代码从mailcontroller调用它:
public class MailController: Controller
{
   byte[] bytes = System.IO.File.ReadAllBytes(FilePath);
   MailModel model= new MailModel();
   model.file = (HttpPostedFileBase)new MemoryPostedFile(bytes, FilePath, filename);
}

现在我可以给变量“file”赋值(httppostedfilebase类型)

10-04 22:29