2

I'm big fan of the MVVM pattern, in particular while using the ASP.NET MVC Framework (in this case v2 preview 2).

But I'm curious if anyone knows how to use it when doing file uploads?

public class MyViewModel
{
    public WhatTypeShouldThisBe MyFileUpload { get; set; }
}

3 Answers 3

3

I have a production asp.net mvc site running with a jQuery multi-file uploader that i wrote. This answer has most of the code included in it so that should get you started with uploads in MVC. The question actually asks about storing the uploaded file in a Stream and i use a byte[], but you'll see in the answer how my code can apply to both scenarios.

1

Usually HttpFileCollection is enough if you are using the standard component (System.IO.Path).

take note that HttpFileCollection is a collection of HttpPostedFile, i.e. you can upload many files at once.

1
  • 1
    It is, but it kind of breaks the MVVM pattern - having everything in one place. I suppose the model could check the http context itself, but that somehow smells all wrong.
    – Kieron
    Nov 8, 2009 at 9:42
1

I would think byte[] would be enough to store the uploaded file, for example in my upload action, I would do sth like this:

        foreach (string file in Request.Files)
        {
            HttpPostedFileBase hpf = Request.Files(file) as HttpPostedFileBase;
            if (hpf.ContentLength == 0)
            {
                continue;
            }


            //This would be the part to get the data and save it to the view
            byte[] origImageData = new byte[(int)hpf.ContentLength - 1 + 1];
            hpf.InputStream.Read(origImageData, 0, (int)hpf.ContentLength);


        }

Hope it helps some how.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.