Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...