区分多个动态文件上载控件

时间:2015-07-14 07:57:26

标签: c# asp.net file-upload

我动态地将多个文件上传添加到我的asp.net页面。 用户可以从页面创建和删除这些文件上载。这个代码用Javascript / JQuery编写:

var opleverpuntCounter = 0;
        function addOpleverpunt() {
            var $opleverpuntContainer = $('#opleverpuntContainer');
            var div = '';
            var divId = 'opleverpunt_' + opleverpuntCounter;
            div = '<div id="' + divId + '"><br />Upload afbeelding situatie vooraf <input id="opleverpuntbeforefile_' + opleverpuntCounter + '" name="opleverpuntbeforefile_' + opleverpuntCounter + '" type="file" accept="image/*" capture="camera" /><br /><label for="opleverpuntdescriptionbefore_' + opleverpuntCounter + '">Situatie omschrijving vooraf</label><br /><textarea type="text" id="opleverpuntdescriptionbefore_' + opleverpuntCounter + '" name="opleverpuntdescriptionbefore_' + opleverpuntCounter + '" rows="5" cols="100"></textarea><br />Upload afbeelding situatie achteraf <input id="opleverpuntafterfile_' + opleverpuntCounter + '" name="opleverpuntafterfile_' + opleverpuntCounter + '" type="file" accept="image/*" capture="camera" /><br /><label for="opleverpuntdescriptionafter_' + opleverpuntCounter + '">Situatie omschrijving achteraf</label><br /><textarea type="text" id="opleverpuntdescriptionafter_' + opleverpuntCounter + '" name="opleverpuntdescriptionafter_' + opleverpuntCounter + '" rows="5" cols="100"></textarea><br /><input id="btn_' + opleverpuntCounter + '" type="button" value="REMOVE X" class="smallButton" /></div>';
            $opleverpuntContainer.append(div);
            $('#btn_' + opleverpuntCounter).click(function () { removeOpleverpunt(divId); });
            opleverpuntCounter++;
        }
        function removeOpleverpunt(element) {
            var $element = $('#' + element);
            $element.remove();
        }

它在每个addOpleverpunt()调用上添加了2个fileupload控件。 nameid都为每个文件上传生成并且是唯一的。

HTML:

<div id="opleverpuntContainer">
</div>

回到服务器端,我使用以下代码来获取和存储上传的文件:

for (int i = 0; i <= Request.Files.Count - 1; i++) {
    HttpPostedFile PostedFile = Request.Files(i);
    if (PostedFile.ContentLength > 0) {
        //Store PostedFile here
        //(Left out to improve question readability)
    }
}

文件上载不是ASP:FileUpload控件,但是常规输入FileUpload控件。

有没有办法区分opleverpuntbeforefile_xopleverpuntafterfile_x? (x是生成的数字)

如果我能够在服务器端获得差异,我将能够将opleverpuntbeforefile存储在一个实体中,将opleverpuntafterfile存储在另一个实体中。

C#或VB.NET中的建议和答案都可以。

1 个答案:

答案 0 :(得分:1)

您可以访问html控件名称:

for (int i = 0; i <= Request.Files.Count - 1; i++)
            {
                HttpPostedFile PostedFile = Request.Files[i];
                var controlName = Request.Files.Keys[i];
                if (PostedFile.ContentLength > 0)
                {
                    //Store PostedFile here
                    //(Left out to improve question readability)
                }
            }