form with multiple upload but allow no upload on edit problems

Posted by minus4 on Stack Overflow See other posts from Stack Overflow or by minus4
Published on 2010-03-27T13:26:13Z Indexed on 2010/03/27 13:33 UTC
Read the original article Hit count: 452

Filed under:
|
|

hiya

i have a section that when created takes in images, however when you edit this item i dont want them to re-upload none changes images just to change a description or name.

i have created this that deals with uploading files:

public void UploadFiles(string currentFileName, FormCollection form)
    {   // loop through all files in form post
        foreach (string file in Request.Files)
        {
            HttpPostedFileBase hpf = Request.Files[file];
            // if no file is uploaded, we could be editing so set to current value
            if (hpf.ContentLength == 0)
            {
                form[file] = currentFileName;
            }
            else
            {   //rename the file unique so we dont clash with names
                var filename = hpf.FileName.Replace(" ", "_").Replace(".", DateTime.Now.Date.Ticks + ".");

                UploadFileName = filename;
                hpf.SaveAs(Server.MapPath("~/Content/custom/" + filename));
                // set the name of the file in our post to the new name
                form[file] = UploadFileName;
            }

        }

        // ensure value is still sent when no files are uploaded on edit
        if(Request.Files.Count <= 0)
        {
            UploadFileName = currentFileName;
        }
    }

all works fine when only one image is required (CurrentFileName), however there is now a new image available taking it to a total of 2 images in the database therefor currentFileName is obsolete. has anyone tackled this and how as i have hit a wall with this one. thought of string[] currentFiles but cant see how to match this into string file in Request.Files.

if it helps i am also working with models for the form so i could pass over the model but i dont think your able to do model.file without some kind of reflection.

help much appreciated.

thanks

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about c#