我的模型中有一个 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/