目前我有一个包含图像文件所有数据的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
}
发布于 2011-09-19 13:40:54
创建派生类,如下所示:
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的地方传递这个类的实例了。
发布于 2011-09-19 13:34:35
不能手动创建HttpPostedFileBase
或派生类(HttpPostedFile
)的实例。这个类只应该由框架实例化。为什么不去掉接受字节数组的第二个控制器操作呢?这没必要。默认的模型绑定器将与接受HttpPostedFileBase
的绑定器一起工作。
https://stackoverflow.com/questions/7466687
复制相似问题