具有多个上传的表单,但不允许上传编辑问题

时间:2010-03-27 13:26:13

标签: c# asp.net asp.net-mvc

我有一个部分,创建时会接收图像,但是当您编辑此项目时 我不希望他们重新上传任何更改图像只是为了更改描述或名称。

我创建了这个来处理上传文件:

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;
        }
    }

当只需要一个图像时(CurrentFileName),所有工作正常,但是现在有一个新图像可用于将数据库中的总共2个图像用于其中,因此currentFileName已过时。有没有人解决这个问题,以及我如何与这个问题碰壁。想到了string [] currentFiles,但是无法看到如何将它匹配到Request.Files中的字符串文件中。

如果它有助于我也使用表单的模型,所以我可以通过模型,但我不认为你能够做model.file没有某种反射。

非常感谢。

感谢

1 个答案:

答案 0 :(得分:0)

解决方案最终拉直了我的脑袋

public void UploadFiles(FormCollection form, NameValueCollection currentFiles)
    {
        foreach (string file in Request.Files)
        {
            HttpPostedFileBase hpf = Request.Files[file];

            if (hpf.ContentLength == 0)
            {
                form[file] = currentFiles[file];
            }
            else
            {
                var filename = hpf.FileName.Replace(" ", "_").Replace(".", DateTime.Now.Date.Ticks + ".");

                UploadFileName = filename;
                hpf.SaveAs(Server.MapPath("~/Content/custom/" + filename));

                form[file] = UploadFileName;
            }

        }

        if(Request.Files.Count <= 0)
        {
            foreach (var file in currentFiles.AllKeys)
            {
                form[file] = currentFiles[file];
            }
        }
    }

anyfeedback和sudgestions将不胜感激