通過修改ajaxFileUpload.js實現多圖片動態上傳並實現預覽


參考:http://smotive.iteye.com/blog/1903606

大部分我也是根據他的方法修改的,我也要根據name實現動態的多文件上傳功能,但是有個問題使我一直無法實現多文件上傳。

就是我發現上傳到后台的文件的數目是你要上傳數量的平方。找了很久才發現這是因為他的代碼還是有點小問題:

 

前段時間做項目有個一個實現多文件上傳的功能,因為以前也沒有接觸過,於是花了好幾天時間才給弄好了,但是回頭一看也沒什么,咋就花了那么長時間呢,看來自己的效率有待提高啊。axFileUpload.js里面的代碼修改一下就能支持多個Id同時上傳,把源碼中的這個:

if (typeof (fileElementId) == 'string') {
            fileElementId = [fileElementId];
        }
        for (var i in fileElementId) {
            //按name取值
            var oldElement = jQuery("input[name=" + fileElementId[i] + "]");
            oldElement.each(function () {
                var newElement = jQuery($(this)).clone();
                jQuery(oldElement).attr('id', fileId);//只將舊元素的Id修改,沒有修改name
                jQuery(oldElement).before(newElement);
                jQuery(oldElement).appendTo(form);
            });
        }

因為是按name上傳,那么我們需要把原頁面中的name屬性給修改掉,再加一行就ok了:

if (typeof (fileElementId) == 'string') {
            fileElementId = [fileElementId];
        }
        for (var i in fileElementId) {
            //按name取值
            var oldElement = jQuery("input[name=" + fileElementId[i] + "]");
            oldElement.each(function () {
                var newElement = jQuery($(this)).clone();
                //jQuery(this).attr('id', fileId);
                jQuery(this).attr('name', fileId);
                jQuery(this).before(newElement);
                jQuery(this).appendTo(form);
            });
        }

,這樣就能實現根據name動態多文件上傳了。

頁面代碼如下:

<body style="background: #FFFFFF;">
    <form action="/Home/UploadImage" id="form1" name="form1" method="post">
        <table style="width: 100%" class="SubTable">
            <tbody>
                <tr class="tr">
                    <td style="width: 80%">
                        <input name="upload" type="file" onchange="IsRepeat(this)" style="width: 100%" />
                    </td>
                    <td style="width: 20%">
                        <input type="button" value="刪除" onclick="deletefile(this, 4)" />
                    </td>
                </tr>
                <tr class="footTr">
                    <td colspan="2">
                        <input type="button" value="添加" onclick="addfile(this, 4)" /></td>
                </tr>
                <tr>
                    <td style="text-align: center" colspan="2">
                        <input type="button" value="提交" id="BtnSub" /></td>
                </tr>
            </tbody>
        </table>
        <table>
            <tr>
                <td style="height: 130px; width: 18%">圖片預覽:
                </td>
                <td style="height: 130px; width: 82%">
                    <table style="width: 100%" class="SubTable">
                        <tbody>
                            <tr class="tr">
                                <td>
                                    <div id="trimagedivBef" style="display: none"></div>
                                </td>
                                <td style="width: 25%">
                                    <input style="width: 100px; height: 80px; display: none" type="image">
                                </td>
                                <td style="width: 25%">
                                    <input style="width: 100px; height: 80px; display: none" type="image">
                                </td>
                                <td style="width: 25%">
                                    <input style="width: 100px; height: 80px; display: none" type="image">
                                </td>
                                <td style="width: 25%">
                                    <input style="width: 100px; height: 80px; display: none" type="image">
                                </td>
                                <td>
                                    <div id="trimagedivAft" style="display: none"></div>
                                </td>
                            </tr>
                            <tr class="footer">
                                <td>
                                    <div id="footerimagedivBef" style="display: none"></div>
                                </td>
                                <td class='footertd' style="width: 25%">
                                    <div style="display: none"><a href="#">刪除</a></div>
                                </td>
                                <td class='footertd' style="width: 25%">
                                    <div style="display: none"><a href="#">刪除</a></div>
                                </td>
                                <td class='footertd' style="width: 25%">
                                    <div style="display: none"><a href="#">刪除</a></div>
                                </td>
                                <td class='footertd' style="width: 25%">
                                    <div style="display: none"><a href="#">刪除</a></div>
                                </td>
                                <td style="text-align: center">
                                    <div id="footerimagedivAft" style="display: none"></div>
                                </td>
                            </tr>

                        </tbody>
                    </table>
                </td>
            </tr>
        </table>
    </form>
</body>

 

js代碼,上傳成功后要實現預覽功能,如果不考慮安全因素的話直接獲取圖片保存在的路徑就行,但是這樣是肯定不被允許的,太不安全,於是把文件放到一個指定的文件夾下

后再通過一個action獲取該圖片的路徑:

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/js/ajaxfileupload.js"></script>
<script type="text/javascript">

    function IsRepeat(obj) {
        var filters = "jpg png bmp";

        var val = $(obj).val();
        var arr = val.split('.');
        if (filters.indexOf(arr[arr.length - 1]) < 0) {
            $(obj).val("");
            alert("請上傳 " + filters + " 格式的圖片", "提示");
            return;
        }
        var count = 0;
        $("input[name='upload']").each(function () {
            if ($(this).val()) {
                if ($(this).val() == val) {
                    if (count >= 1) {
                        $(this).val("");
                        alert("已上傳該圖片,請重新選擇!", "提示");
                        return;
                    }
                    count++;
                }
            }

        })
    }

    function deleteImage(val) {
        if (confirm("是否刪除圖片?")) {
            falg = false;
            var id = "#del_" + val;
            $(id).parent().remove();
            id = "#image_" + val;
            $(id).parent().remove();
            $("#trimagedivAft").closest("td").before("<td style=\"width:25%\"><input style=\"width:100px;height:80px;display:none\" type=\"image\" src=\"#\"></td>");
            $("#footerimagedivAft").closest("td").before("<td class='footertd' style=\"text-align:center;width:25%\"><div style=\"display:none\"><a href=\"#\">刪除</a></div></td>");
        }
    }

    function addfile(obj, maxNum) {
        $(obj).closest("tr").before("  <tr class=\"tr\"><td width=\"80%\"><input name=\"upload\" type=\"file\" onchange=\"IsRepeat(this)\" style=\"width:100%;\" /></td><td width=\"20%\"><input type=\"button\" value=\"刪除\" onclick=\"deletefile(this," + maxNum + ");\" /> </td></tr>");
        //檢測是否已經到達最大的個數,需要隱藏添加按鈕
        if (maxNum > 0) {
            if ($(obj).closest("table").children().children(".tr").length == maxNum) {
                $(obj).hide();
            }
        }
        return false;
    }

    function deletefile(obj, maxNum) {
        //檢測是否已經到達最大的個數,需要隱藏添加按鈕
        if (maxNum > 0) {
            var inputAdd = $(obj).closest("table").children().children(".footTr").children().children("input");
            var num = $(obj).closest("table").children().children(".tr").length;
            $(obj).closest("tr").remove();
            if ((num - 1) < maxNum) {
                inputAdd.show(); //定位到添加按鈕
            }
        }
        else {
            $(obj).closest("tr").remove();
        }
        return false;
    }
    var falg = false;
    var countFalg = 0;

    $("#BtnSub").click(function () {
        var falg = true;
        $("input[name='upload']").each(function () {
            if ($(this).val() == "") {
                falg = false;
            }
        })

        if (!falg) {
            alert("上傳圖片不能為空", "提示");
            return;
        }
        $.ajaxFileUpload({
            url: "@Url.Action("PhotoUploadImage", "Home")",
            secureuri: false,
            fileElementId: 'upload',//修改了ajaxFileUpload.js源碼,支持上傳多個name相同的文件,修改處在45行~57行
            dataType: 'json',
            success: function (data, status) {
                
                //alert(data['status'] + '-----' + data['fileName'] + '-----' + data['extName']);
                if (data != null) {
                    var returnValue = data['filePath'];
                    if (returnValue) {

                        var array = returnValue.split('|');
                        var retLen = array.length;
                        var ss = "";
                        for (var i = 0; i < array.length; i++) {
                            if (array[i]) {
                                var len = $("#trimagedivAft").closest("tr").children(".td").length;
                                var ran = Math.ceil(Math.random() * 9999999999999999);
                                var fp = "";

                                fp = "@Url.Action("ShowImage", "Home")" + "?filePath=" + array[i].split(',')[0];
                                    if (!falg) {
                                        $("#trimagedivAft").parent().prev().remove();
                                        $("#footerimagedivAft").parent().prev().remove();
                                        $("#trimagedivBef").closest("td").after("<td class='td' style=\"width:25%\"><input width='100px' id='image_" + ran + "' height='80px' value=" + array[i] + "  src=" + fp + " type=\"image\"/></td>");

                                        $("#footerimagedivBef").closest("td").after("<td class='footertd' style=\"text-align:center;width:25%\"><div onclick='deleteImage(" + ran + ")'  id='del_" + ran + "'><a href=\"#\">刪除</a></div></td>");
                                    } else {
                                        $("#trimagedivBef").parent().next().remove();
                                        $("#footerimagedivBef").parent().next().remove();
                                        $("#trimagedivAft").closest("td").before("<td class='td' style=\"width:25%\"><input width='100px' id='image_" + ran + "' height='80px' value=" + array[i] + " src=" + fp + " type=\"image\"/></td>");
                                        $("#footerimagedivAft").closest("td").before("<td class='footertd' style=\"text-align:center;width:25%\"><div onclick='deleteImage(" + ran + ")' id='del_" + ran + "'><a href=\"#\">刪除</a></div></td>");
                                    }
                                    countFalg++;
                                    if (countFalg >= 4) {
                                        falg = true;
                                    }
                                }

                            }
                        }
                    }
                },
            error: function (data, status, e) {
                //alert(e);
                alert("上傳失敗");
                return false;
            }
        })
    })
</script>

后台上傳代碼:

//上傳附件
        public void PhotoUploadImage(object sender, EventArgs e)
        {
            var files = Request.Files;
            DateTime now = DateTime.Now;
            string time = DateTime.Now.ToString("yyyy-MM");
            string tmpPath = Server.MapPath("~/App_Data/upload/images/" + time);
            string filesPathArr = "";
            if (files != null && files.Count > 0)
            {
                for (int i = 0; i < files.Count; i++)
                {

                    var file = files[i];

                    if (Directory.Exists(tmpPath) == false)//如果不存在就創建file文件夾
                    {
                        Directory.CreateDirectory(tmpPath);
                    }
                    double fileSize = file.ContentLength;

                    Thread.Sleep(10);
                    string name = Path.GetFileNameWithoutExtension(file.FileName);
                    string extName = Path.GetExtension(file.FileName);
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfffff") + extName;
                    try
                    {
                        string filePath = tmpPath + "/" + fileName;
                        file.SaveAs(filePath);

                        filesPathArr += "/App_Data/upload/images/" + time + "/" + fileName + "," + fileSize + "," + name + "," + extName + "|";
                    }
                    catch (Exception ex)
                    {
                        Response.Write(@"{
                                status : 'error',
                                msg : '" + ex.Message + @"'
                                }");
                        Response.End();
                        return;
                    }
                }
            }

            Response.Write(@"{
                    status : 'success', 
                    msg: { 
                        Origin : ''
                    },
                    filePath:'" + filesPathArr + @"'
                }");
        }

獲取上傳圖片路徑的代碼:

public ActionResult ShowImage(string filePath = "")
        {
            string path = Server.MapPath("~" + filePath);
            return base.File(path, "Image/jpeg");
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM