Reputation: 8308
I have an application that allows users to upload word and pdf documents. I also have a class in my model that gathers some metadata about the file (i.e., file size, content type, etc.).
I want to centralize some of the "save" functionality (both saving the metadata to the database, and saving the actual file to the server). I would like to pass the HttpPostedFileBase to my Service layer that will then use the built-in .SaveAs(filename) functionality. However, I can't seem to figure out how to pass the file type to another method. I've tried the below:
public ActionResult Index(HttpPostedFileBase uploadedDocument)
{
string fileName = "asdfasdf";
SomeClass foo = new SomeClass();
//this works fine
uploadedDocument.SaveAs(fileName)
//this does not work
foo.Save(uploadedDocument, fileName);
}
public class SomeClass
{
public void Save(HttpPostedFile file, string fileName)
{
//database save
file.SaveAs(fileName);
}
}
When I try to pass the HttpPostedFile into the Save method on SomeClass, there is a compiler error (because in the above, uploadedDocument is of type HttpPostedFileBase, not HttpPostedFile).
However, if I try to cast uploadedDocument to HttpPostedFile, it does not work.
So, specifically, how can I pass an HttpPostedFileBase to another method? Or, more generally, if I were to pass the HttpPostedFileBase.InputStream to another method, how can I save that document to the server? Note that the document is not an image and I am not streaming the response to the user, so writing to the response stream isn't appropriate...I think.
Upvotes: 0
Views: 2610
Reputation: 123498
You should just use HttpPostedFileBase
, for example in the SomeClass.Save method. The HttpPostedFile
class doesn't actually derive from the HttpPostedFileBase
, so you're bound to get the compiler error you noticed. You might also see the documentation for HttPostedFileWrapper
which is used for the reverse scenario: passing HttpPostedFile
to a method that accepts HttpPostedFileBase
.
Upvotes: 4