c# - 如何将文件发布到 Controller 中的变量(类型为 'HttpPostedFileBase')

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

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

    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 赋值。如何在相应的 Controller 中为 file 赋值?

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

谢谢!

最佳答案

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

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

我在 MailModel 中为 HttpPostedFileBase 创建了一个派生类。

    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)

关于c# - 如何将文件发布到 Controller 中的变量(类型为 'HttpPostedFileBase'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726110/

相关文章:

r - 如何将文件的多行读入数据帧的一行

c# - 从 Office 选择中获取 HTML

asp.net-mvc - 将 Action 方法参数传递给asp.net mvc中的ActionFilterAttribute

asp.net-mvc - 从 MVC 中的 Controller 确定局部 View 的模型

c++ - C/C++ 中的头文件,标准?

arrays - 使用swift读入文本文件

c# - 如何在 c# gui 中调用我的 c++ 程序?

c# - 如何使用 AngleSharp 从 html 字符串中获取所有评论标签?

c# - 如何在 DataGridViewComboBoxCell 中选择一个值?

c# - 更改 Kendo UI 上传小部件的文本