如何创建HttpPostedFileBase实例(或其继承类型)

Che*_*hen 24 .net c# asp.net-mvc asp.net-mvc-3

目前我有一个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
}
Run Code Online (Sandbox Code Playgroud)

Muh*_*han 43

创建派生类,如下所示:

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);
}
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以传递此类的实例,其中需要HttpPostedFileBase.

  • 只是想在你创建后展示如何使用MemoryFile:`string filePath = Path.GetFullPath("C:\\ images.rar"); FileStream fileStream = new FileStream(filePath,FileMode.Open); MemoryFile fileImage = new MemoryFile(fileStream,"application/x-rar-compressed","images.rar");` (3认同)