如何在控制器中将文件发布到变量(类型为' HttpPostedFileBase')

时间:2018-04-09 05:27:11

标签: c# asp.net-mvc file file-upload httppostedfilebase

我的模型中有一个变量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?
    }

谢谢!

1 个答案:

答案 0 :(得分:3)

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

    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