如何创建HttpPostedFileBase(或其继承类的一个实例)或其、实例、HttpPostedFileBase

2023-09-04 01:07:49 作者:回眸゛似水流年

目前我有一个字节[] 包含图像文件的所有数据,只是想建立 HttpPostedFileBase ,这样我就可以使用,而不是创建一个新的重载之一的现有方法。

 公众的ActionResult保存(HttpPostedFileBase文件)

公众的ActionResult保存(byte []的数据)
{
    //希望我可以在这里再构造HttpPostedFileBase的一个实例
    返回保存(文件);

    //而不是写了很多类似codeS的
}
 

解决方案

创建一个派生类,如下所示:

 类MemoryFile:HttpPostedFileBase
{
流流;
字符串的contentType;
字符串文件名;

公共MemoryFile(流流,字符串的contentType,字符串文件名)
{
    this.stream =流;
    this.contentType的contentType =;
    this.fileName =文件名;
}

公众覆盖INT CONTENTLENGTH
{
    {返回(INT)stream.Length; }
}

公共重写字符串的ContentType
{
    {返回的contentType; }
}

公众覆盖字符串文件名
{
    {返回文件名; }
}

公共覆盖流的InputStream
{
    {返回流; }
}

公众覆盖无效另存为(字符串文件名)
{
    使用(var文件= File.open方法(文件名,FileMode.CreateNew))
        stream.CopyTo(文件);
}
}
 
新型电力系统样板来了 全面阐述其内涵 内容 建设步骤 意义

现在,你可以通过这个培训班里HttpPostedFileBase预期的实例。

Currently I have a byte[] that contains all the data of an image file, just want to build an instance of HttpPostedFileBase so that I can use an existing method, instead of creating a new overload one.

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
}

解决方案

Create a derived class as follows:

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);
}
}

Now you can pass instance of this class where HttpPostedFileBase is expected.