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

一曲冷凌霜 提交于 2019-12-12 05:28:12

问题


I am currently experiencing the exact same problem as here: Multiple File Upload with jQuery [removing file then adding it again].

So far I have managed this:

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

Also have this for file upload in 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>

Both the error message and the server address, between {}, are actually properly coded, just not displayed here.

My apologies for the length of code.

I need a simple way of adding up to 3 files as attachments, then if the user wishes to add one, remove it and add it again, it must be working. My code works fine on Firefox, but of course this sort of excuse does not work in a company.

Most teams here use plugins, but I am out of such option, as I have already tryed it, and was 20 times harder to put it working, due to the enormous ammount of changes the code would have to suffer (changes I have neither time nor authorization to proceed with).

Any help, please? One of the comments in the post I linked says the fiddle made was working fine, but I tested it, and same issue, on chrome and IE nothing, on firefox it works fine.

Furthermore I must add that I have only one year of experience in programming in general, most of it for mobile platform Android, which does not equip me with the required skills to understand most of the working engine behind browsers or even web browsing in general.

Thank you so much in advance.


回答1:


ended up giving up the idea of uploading to a temporary folder, and them move the files when the message is sent. rather, now, I send everything on the same FormData object (using a mixture of both here http://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/ and here JQuery ajax file upload to ASP.NET with all form data, and for now it is working (which is actually enough for me)...



来源:https://stackoverflow.com/questions/37488549/multiple-file-upload-jquery-asp-net-add-remove-then-add-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!