如何在 MVC 的多文件上传视图中显示文件大小和文件名

How to show size of the file along with file name in a multiple file upload view of MVC

我有一个视图允许用户一次上传多个,如下所示

<label class="control-label">Files:</label>
<div id="fileUploadContainer">
    <div id="uploadContainer" style="height:30px">
        <input type="file" id="file1" name="file1" onchange="ValidateSingleInput(this);" />
    </div>
    <div class="controls">
        <div id="fileappend">
            <div id="fileappendContainer">
                <output id="filesSize"></output>
            </div>
        </div>
    </div>
</div>
<a id="btnAdd" href="#">Add Another</a>

代码"Add Another"点击:

$(function () {
    $('#btnAdd').click(function (e) {
        e.preventDefault();
        var htmlFormatDiv = $("<div id='uploadContainer' style='height:30px'></div>");
        var htmlFormatFile = $("<input type='file' onchange='ValidateSingleInput(this);' />");
        var totalFileCount = $("#fileUploadContainer").children("div").length;
        var fuData = document.getElementById('<%= file1.ClientID %>');
        htmlFormatFile.attr("id", "file1");
        htmlFormatFile.attr("name", "file1");
        htmlFormatDiv.attr("id", "uploadContainer");
        htmlFormatDiv.append(htmlFormatFile);
        $("#fileUploadContainer").append(htmlFormatDiv);
        $("#filesSize").append(htmlFormatDiv);
    });
});

限制文件上传扩展名类型和显示文件大小的代码

var _validFileExtensions = [".jpg", ".jpeg", ".pdf"];
function ValidateSingleInput(oInput) {
    if (oInput.type == "file") {
        var sFileName = oInput.value;
        if (sFileName.length > 0) {
            var fsize = sFileName.size;
            if (fsize > 4048576) {
                alert(fsize + " bites\nToo big!");
            }
            var blnValid = false;
            for (var j = 0; j < _validFileExtensions.length; j++) {
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) 
                { 
                    blnValid = true;
                    $('#filesSize').append('Size - ' + ((oInput.files[0].size) / 1024 / 1024).toFixed(2) + 'mb' + '<br />');
                    break;
                }
            }
            if (!blnValid) {
                alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                oInput.value = "";
                return false;
            }
        }
    }
    return true;
}

现在,当我上传文件时,我得到的结果低于 O/P

当我再次单击任何现有的浏览按钮浏览另一个文档时出现问题。旧文件的大小将保留在那里,新文件的大小将附加到最后一个文件名,而不管单击的浏览按钮如何。 有什么办法可以避免同样的情况吗?

还有比这更简单的方法吗

控制器

public ActionResult file_upload(IEnumerable<HttpPostedFileBase> file1)
{
    foreach (var file in file1)
    {
        if (file != null)
        {
            if (file.ContentLength > 0)
            {
            }
        }
    }
}

你的主要问题是你生成无效的 html 因为重复的 id 属性和 jQuery select 或者 $('#filesSize').append(... 只会 select 第一个元素 id。您需要改用 class 名称,并使用相对 select 或 select 要更新的正确元素。

不过,我会建议对您的实施进行一些其他更改。

首先,考虑对文件大小使用 ValidationAttribute,这将为您提供客户端和服务器端验证。请参阅 Client-side File Upload Size Validation in ASP.NET MVC 以获取实现它的示例。

其次,创建一个可以克隆、更新和附加到 DOM 的模板。您当前的代码正在做一些奇怪的事情,包括将新的 div 添加到 <div id="fileUploadContainer"> 和第一个 <output id="filesSize"> elements. Its not really clear why you are using anelement or whatvar fuDatais (it would beundefined`) 或者如何它被使用。您的观点是

@using (Html.BeginForm(.....))
{
    <div id="fileUploadContainer"></div>
    <a id="btnAdd" href="#">Add a file</a>
}
// template
<div id="template" style="display:none;">
    <div class="uploadContainer" style="height:30px">
        <input type="file" class="file" name="files" />
    </div>
    <div class="controls">
        <div class="fileappend">
            <div class="fileappendContainer">
                <span class="filesSize"></span>
            </div>
        </div>
    </div>
</div>

然后脚本将是(不包括您的验证码)

var container = $('#fileUploadContainer');
var template = $('#template');
$('#btnAdd').click(function() {
    var clone = template.clone();
    container.append(clone.html());
    $(this).text('Add another file');
});
container.on('change', '.file', function() {
    var file = $(this).get(0).files[0];
    var fileSize = 'Size: ' + Math.round(file.size / 1024) + ' KB'
    $(this).parent('.uploadContainer').next('.controls').find('.filesSize').text(fileSize);
});

请注意,如果您要实现 FileSizeAtribute,那么会对模板进行一些额外的更改(为输入提供索引名称属性,包括输入中的 data-val-* 属性并为验证消息添加 html),您需要在添加新文件输入时重新解析验证器。