多文件上传的jQuery asp.net添加,删除然后重新添加 [英] multiple file upload jquery asp.net add, remove then add again

查看:222
本文介绍了多文件上传的jQuery asp.net添加,删除然后重新添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前遇到的相同问题如下:<一href=\"http://stackoverflow.com/questions/25093327/multiple-file-upload-with-jquery-removing-file-then-adding-it-again\">Multiple文件上传与jQuery [删除文件,然后重新添加] 。

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

也有这个在HTML文件上传:

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>

这两个错误信息和服务器地址,之间{},实际上是正常codeD,只是没有显示在这里。

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

我的道歉为code的长度。

My apologies for the length of code.

我需要加入至多3个文件作为附件的一个简单的方法,则如果用户希望增加一个,将其删除,然后重新添加,必须将其工作。我的code正常工作在Firefox,但当然,这种辩解并没有在公司工作。

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.

大多数队伍在这里使用的插件,但我出这样的选择,因为我已经tryed它,是由于变化的巨大ammount的的code将不得不遭受难以把它的工作,20倍(改变我既没有时间,也没有授权继续进行)。

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

任何帮助,好吗?在一个联系我的帖子的评论中说,小提琴制作工作正常,但我测试了它,同样的问题,在Chrome和IE什么,在Firefox它工作正常。

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.

此外,我必须说明,我的经验只有一年的编程一般来说,大部分的移动平台Android的,这并不装备我所需要的技能,了解大部分的工作引擎背后的浏览器甚至是网页浏览一般。

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.

感谢你这么多提前。

推荐答案

最终放弃上传到一个临时文件夹的想法,并把它们移动文件发送邮件时。而现在,我把一切都在同一FORMDATA对象(这里<一个使用两者的混合物href=\"http://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/\" rel=\"nofollow\">http://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/这里<一个href=\"http://stackoverflow.com/questions/29096426/jquery-ajax-file-upload-to-asp-net-with-all-form-data\">JQuery AJAX文件上传到所有的表单数据 ASP.NET和现在它在工作(这实际上对我来说足够的)...

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

这篇关于多文件上传的jQuery asp.net添加,删除然后重新添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆