views:

65

answers:

4

I've been working all weekend on a Messaging system for my website so users can send and receive messages on my site internally.

I have my table schemas worked out, and right now I can send basic messages to different users.

Now, I'm working on the attachments portion.

How can I create my action methods so that they accept Files? Ideally I would like to allow for a controller action that accepts an arbitrary number of files. Once they have been passed into the controller action I'm going to save them somewhere on my webserver.

Can anyone show me an example of a controller action that accepts files as part of its parameters?

+3  A: 

(Error handling omitted.)

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult FilePost()
    {
        for (var i = 0; i < Request.Files.Count; i++)
        {
            var filebase = Request.Files.Get(i);
            string filePath = Server.MapPath(Url.Content("~/Content/UserContent/"));
            var fileName = // whatever
            filebase.SaveAs(Path.Combine(filePath, fileName));
         }

        return RedirectToAction("Something");
    }
Craig Stuntz
Make sure you add the enctype attribute to your form tag aswell. E.g. `<form action="/controller/action" method="post" enctype="multipart/form=data"> ... blah ... </form>`
Charlino
+2  A: 

I believe the object you're looking for is Request.Files example snippet below.

foreach (string file in Request.Files) {
    var hpf = Request.Files[file];

    if (hpf.ContentLength == 0)
        continue;

    myFileEntity.ContentType = hpf.ContentType;
    myFileEntity.File = hpf.InputStream.ToByteArray();
    myFileEntity.FileName = hpf.FileName;
}
jcm
+2  A: 

Here is a post on how to Upload file with ASP.NET MVC

CSharpAtl
Not sure why this was down-voted. It's not a *great* answer, but it isn't a *bad* answer, either. So I'll give it +1 just to bring it back to 0...
Craig Stuntz
I did not see the need to rewrite everything...the blog entry explains everything pretty well.....no need to reinvent the wheel.
CSharpAtl
A: 

Check out my answer in this post.

Having troubles calling a controller post method

griegs