Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an instance of HttpPostedFileBase(or its inherited type)

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 } 
like image 563
Cheng Chen Avatar asked Sep 19 '11 05:09

Cheng Chen


People also ask

What is HttpPostedFileBase in MVC?

The HttpPostedFileBase class is an abstract class that contains the same members as the HttpPostedFile class. The HttpPostedFileBase class lets you create derived classes that are like the HttpPostedFile class, but that you can customize and that work outside the ASP.NET pipeline.


2 Answers

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.

like image 78
Muhammad Hasan Khan Avatar answered Sep 24 '22 03:09

Muhammad Hasan Khan


You cannot manually create an instance of HttpPostedFileBase or derived classes (HttpPostedFile). This class is only supposed to be instantiated by the framework. Why don't you get rid of the second controller action that takes a byte array? It's not necessary. The default model binder will work fine with the one taking a HttpPostedFileBase.

like image 39
Darin Dimitrov Avatar answered Sep 25 '22 03:09

Darin Dimitrov