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

29

目前我有一个包含图像文件所有数据的 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
}

你是否成功解析了存储在byte[]中的文件并得到了答案?我的代码一直保留着content disposition等内容。 - Devela
2个回答

53
创建一个派生类,如下所示:
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。


4
只是想展示如何在创建后使用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"); - Murat
你,先生,是个天才! - Ibrahim Dauda
请记得在完成操作后关闭/处理 fileStream,否则文件将会一直处于打开状态(且无法访问)。 - Dan Diplo

1

您不能手动创建HttpPostedFileBase或其派生类(HttpPostedFile)的实例。该类只应由框架实例化。为什么不删除掉那个接受字节数组的第二个控制器操作呢?这是不必要的。默认的模型绑定器将与接受HttpPostedFileBase的操作一起正常工作。


1
JS开发人员向我发送了byte[],这个问题发生在用户从剪贴板粘贴图像而不是选择图像文件上传时。 - Cheng Chen
@Danny Chen,js 发送 byte[]?这看起来非常奇怪。使用了什么协议? - Darin Dimitrov
1
他正在向我发送一个base64字符串,这个行为是由第三方js编辑器执行的。 - Cheng Chen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接