多文件上传 jquery asp.net 添加、删除然后再次添加

multiple file upload jquery asp.net add, remove then add again

我目前遇到与此处完全相同的问题:Multiple File Upload with jQuery [removing file then adding it again]

到目前为止我已经做到了:

function UploadFile(ajaxUrl, event)
{
    if ($("p[id=alertFileCount]").is(":visible"))
        $("p[id=alertFileCount]").hide();

    if (ajaxUrl == '' || ajaxUrl === undefined)
    {
        ShowErrorAlertUploadFiles();
        return;
    }

    var fileList = [];
    var files = event.target.files;
    var $elem = $("a.attachMessageBtn");

    if (ValidateFilesCount(files) === false)
    {
        ShowErrorAlertUploadFiles();
        return;
    }

    for (var i = 0; i < files.length; i++)
    {
        var file = files[i];
        var ext = $("#fileAttach").val().split('.').pop().toLowerCase();
        event.stopPropagation();
        event.preventDefault();

        if (ValidateFiles(file, ext) === false)
            return;
        else
        {
            var finalData = [];
            var evtOnClick = $elem.attr('onclick');
            var postData = new FormData();
            postData.append("file", file);

            // contentType: false _> Set content type to false as jQuery will tell the server its a query string request.
            // enctype: "multipart/form-data" _> Compatibility with IE.
            $.ajax({
                url: ajaxUrl + "?a=setUploadFile",
                type: "POST",
                data: postData,
                cache: false,
                processData: false,
                contentType: false,
                forceSync: false,
                enctype: "multipart/form-data",
                beforeSend: function (jqXHR, settings)
                {
                    $elem.attr('onclick', null);
                },
                success: function (data, textStatus, jqHXR)
                {
                    fileList.push(file);
                    finalData = data.split('|');
                    UpdateFileUploadUI(finalData);
                },
                error: function (jqHXR, textStatus, errorThrown)
                {
                    ShowErrorAlertUploadFiles();

                    if (jqXHR.getAllResponseHeaders() !== '')
                        LogError(errorThrown, this.url, 0, 0, this.type + ': ' + this.data);
                },
                complete: function (jqXHR, textStatus)
                {
                    $elem.attr('onclick', evtOnClick);
                }
            });
        }
    }
}

function ValidateFilesCount(files)
{
    var currFiles = files.length;
    var currAttachFilesAddRemove = $("#attachFilesAddRemove > div.attached").length;
    var currFileTempNames = $("#fileTempNames").val().split('?').length;

    if (currFiles > 3
        || currAttachFilesAddRemove > 3
        || currFileTempNames > 3
        || currFiles + currAttachFilesAddRemove > 3)
    {
        ShowNoContentUploadFiles('{ERROR MESSAGE HERE}');
        return false;
    }
    return true;
}

function ValidateEmptyFile(file)
{
    if (file.size == 0)
        return false;

    return true;
}

function ValidateFileMaxSize(file)
{
    var maxFileSize = 4 * 1024 * 1024;

    if (file != null && file.size > maxFileSize)
        return false;

    return true;
}

function ValidateFileExt(ext)
{
    if ($.inArray(ext, ['exe']) > -1)
        return false;

    return true;
}

function ShowNoContentUploadFiles(text)
{
    var $pNoContent = $("p[id=alertFileCount]");

    $pNoContent.html(text);
    $pNoContent.show().css({ opacity: 1, display: "block" });
}

function ValidateFiles(file, ext)
{
    var text = '';
    var isInvalid = false;

    if (ValidateEmptyFile(file) === false)
    {
        text = 'You may only upload files with over 0bytes.';
        isInvalid = true;
    }

    if (ValidateFileMaxSize(file) === false)
    {
        text = 'You may only upload files with up to 4MB.';
        isInvalid = true;
    }

    if (ValidateFileExt(ext) === false)
    {
        text = 'Files with extension \'.exe\' will not be uploaded.';
        isInvalid = true;
    }

    if (isInvalid === true)
    {
        ShowNoContentUploadFiles(text);
        return false;
    }
    return true;
}

function UpdateFileUploadUI(finalData)
{
    UpdateFilesAddRemove(finalData);

    UpdateFileDataMediaUID();
}

function UpdateFilesAddRemove(finalData)
{
    var fileData = finalData[0] + '|' + finalData[1];

    $("div[id=attachFilesAddRemove]").append("<div class='attached' data-mediauid='"
        + fileData
        + "'><a class='file' style='cursor: pointer;'>"
        + finalData[0]
        + "</a><a onclick=\"RemoveAttachedFile(\'"
        + fileData
        + "\');\" style='cursor: pointer;' class='close'></a></div>");
}

function UpdateFileDataMediaUID()
{
    var listData = '';

    $("div[id=attachFilesAddRemove] > .attached").each(function (i, obj)
    {
        listData += $(obj).attr("data-mediauid") + '?';
    });

    listData = listData.slice(0, -1);

    $("input[id=fileTempNames]").val(listData);
}

function RemoveAttachedFile(fileData)
{
    if (fileData == '' || fileData === undefined)
        return;

    // Update the names in fileTempNames.
    var result = '';
    var $iElem = $("input[id=fileTempNames]");
    var names = $iElem.val().split('?');

    for (var i = 0; i < names.length; i++)
    {
        if (names[i] != '' && names[i] != fileData)
        {
            result += names[i] + '?';
        }
    }

    $iElem.val(result);

    $("div[data-mediauid='" + fileData + "']").remove();
}

function ShowErrorAlertUploadFiles()
{
    SetAlertBoxTitleAndText('', 'At the moment it was not possible to proceed with the upload, please try again later.', true);
    ShowAlertBox();
}

在 html 中也有这个用于文件上传:

<a class="attachMessageBtn" style="cursor: pointer; position: relative; overflow: hidden; direction: ltr;">Adicionar ficheiro
    <input id="fileAttach" type="file" name="file" multiple="multiple" title="Adicionar ficheiro" style="position: absolute; right: 0px; top: 0px; font-family: Arial; font-size: 118px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0;" onchange="UploadFile('<%=VirtualPathUtility.ToAbsolute({SERVER ADDRESS HERE})%>', event);" accept="*">
</a>
<input id="fileTempNames" type="hidden" value="">
<div class="attachFiles" id="attachFilesAddRemove"></div>
<p id="alertFileCount" style="display: none;"></p>

在{}之间的错误消息和服务器地址实际上都已正确编码,只是没有显示在这里。

对于代码的长度,我深表歉意。

我需要一种添加最多 3 个文件作为附件的简单方法,然后如果用户希望添加一个,将其删除并再次添加,它一定可以工作。我的代码在 Firefox 上运行良好,但这种借口在公司当然行不通。

这里的大多数团队都使用插件,但我没有这样的选择,因为我已经尝试过,并且由于代码必须进行大量更改而使其工作要困难 20 倍(我既没有时间也没有授权进行更改)。

有什么帮助吗?我链接的 post 中的评论之一说 fiddle 工作正常,但我测试了它,同样的问题,在 chrome 和 IE 上没有,在 firefox 上它工作正常。

此外,我必须补充一点,我一般只有一年的编程经验,其中大部分是针对移动平台的 Android,这并没有让我具备了解大部分工作引擎所需的技能在浏览器之后,甚至是一般的网页浏览。

在此先感谢您。

最终放弃了上传到临时文件夹的想法,他们在发送邮件时移动了文件。相反,现在,我将所有内容都发送到同一个 FormData 对象上(在这里 http://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/ and here 混合使用两者,现在它正在工作(这对我来说实际上已经足够了)...