views:

712

answers:

2
+2  Q: 

File upload in MVC

Hi all,

I'm trying to upload files within MVC. Most solution I saw on SO is use webform. I don't want to use that and personly prefer using streams. How do you implement RESTful file uploading on MVC? Thanks!

+4  A: 

Edit: And just when you think you have it all figured out you realise that there is a better way. Check out http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

Original: I am not sure that I understand your question 100%, but I assume that you want to upload a file to a url that looks something like http://{server name}/{Controller}/Upload? This would be implemented exactly like a normal file upload using web forms.

So your controller has an action named upload and looks similar to this:

//For MVC ver 2 use:
[HttpPost]
//For MVC ver 1 use:
//[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Upload()
{
    try
    {
        foreach (HttpPostedFile file in Request.Files)
        {
            //Save to a file
            file.SaveAs(Path.Combine("C:\\File_Store\\", Path.GetFileName(file.FileName)));

            // * OR *
            //Use file.InputStream to access the uploaded file as a stream
            byte[] buffer = new byte[1024];
            int read = file.InputStream.Read(buffer, 0, buffer.Length);
            while (read > 0)
            {
                //do stuff with the buffer
                read = file.InputStream.Read(buffer, 0, buffer.Length);
            }
        }
        return Json(new { Result = "Complete" });
    }
    catch (Exception)
    {
        return Json(new { Result = "Error" });
    }
}

In this case I am returning Json to indicate success, but you can change this to xml (or anything for that matter) if needed.

Geoff
And, obviously ALWAYS make sure you aren't just accepting any old junk from a user. Minimum check would be content type, extension and run it through a virus scanner before you trust it. :)
ZombieSheep
Vary true, ZombieSheep, you need to check EVERYTHING that a client sends on the server side, even if you have validated on the client, but all the "production ready" stuff gets in the way of the point you are trying to demonstrate.
Geoff
Thanks! But that's the way I use currently. I don't want to save any file on the server because it will pollute the server.
Roy
@Roy, if you don't want to save a file then use the code after the // * OR * comment
Geoff
Okay, I will get the stream from the file. Thanks!
Roy
+1  A: 

Hi Does the above code realy work ? have you tested it? When i tried it, I got an 404 error, "page not found".

By the way.I´m using MVC 2 on XP

So i removed the [HttpPost] and suddenly the page was found, but I've got the following error instead.

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet

so I added return Json(new { Result = "Complete" }, JsonRequestBehavior.AllowGet);

and now it pops up dialog box asking me if I want to save this file. Qe! Which file??? I have not passed any file. So i choosed save in the dialog and another dilogbox popped upp asking me for the file to save.

I choosed a path and filename mytestfile.txt and and pressed save

I then opened the mytestfile.txt in a texteditor and discovered the following content {"Result":"Complete"} Should´nt this content be returned to the client instead of beeing saved in the file?

Should not the file dialog ask me for a file to add from the clientside, and pop up a file chooser dialog instead?

So for now I´m very confused, please help me out on this.

Is it possible to skip all the dialog garbage? I want to send a datastream from an Android mobile phone to a MVC controller. Is this so hard to implement in MVC?

regards Berndt

Berndt