目前,我有一个byte[]
,其中包含图像文件的所有数据,只想构建HttpPostedFileBase
的实例,以便可以使用现有方法,而不必创建新的重载方法。
public ActionResult Save(HttpPostedFileBase file)
public ActionResult Save(byte[] data)
{
//Hope I can construct an instance of HttpPostedFileBase here and then
return Save(file);
//instead of writing a lot of similar codes
}
最佳答案
创建一个派生类,如下所示:
class MemoryFile : HttpPostedFileBase
{
Stream stream;
string contentType;
string fileName;
public MemoryFile(Stream stream, string contentType, string fileName)
{
this.stream = stream;
this.contentType = contentType;
this.fileName = fileName;
}
public override int ContentLength
{
get { return (int)stream.Length; }
}
public override string ContentType
{
get { return contentType; }
}
public override string FileName
{
get { return fileName; }
}
public override Stream InputStream
{
get { return stream; }
}
public override void SaveAs(string filename)
{
using (var file = File.Open(filename, FileMode.CreateNew))
stream.CopyTo(file);
}
}
现在,您可以在需要HttpPostedFileBase的地方传递此类的实例。
关于c# - 如何创建HttpPostedFileBase(或其继承的类型)的实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7466687/