天天看點

我的程式設計筆記-asp.net批量上傳圖檔

前幾天做了批量上傳圖檔的功能,看似簡單,其實也不簡單,主要還是細節!

卍★http://file.★yiyuen.com★/file/download/46347卍true卍※http://39.★107.★255.★75:8010※

先看圖

我的程式設計筆記-asp.net批量上傳圖檔

文字說明的textbox經過了處理然後支援了工具欄

<script src="../Content/My97DatePicker/WdatePicker.js"></script>

     <link href="../Content/kindeditor/themes/qq/qq.css" target="_blank" rel="external nofollow" rel="stylesheet" />  

    <script src="../Content/kindeditor/kindeditor-all-min.js"></script>

<script charset="utf-8" src="../Content/kindeditor/lang/zh-CN.js"></script> 

<script>

   var editor1;

KindEditor.ready(function(K) {

 editor1 = K.create('#<%=body.ClientID%>', { 

   uploadJson: '/handler/ke_upload.ashx',

   items: [

'source', '|','fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',

'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',

'insertunorderedlist', '|', 'emoticons', 'image', 'multiimage', 'link'],

   afterChange: function () {

       this.sync();

   },

   newlineTag: "br"

}); 

});

</script>

以下是沒有工具欄的頁面代碼

<%@ Page Title="" Language="C#" MasterPageFile="~/adnn1n/admintopfoot.Master" AutoEventWireup="true" CodeBehind="moreadd.aspx.cs" Inherits="JiuFen.PPL.Web.adnn1n.moreadd" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

 <h1 class="page-header">

         <asp:Literal ID="lith1" Text="新增" runat="server"></asp:Literal></h1>

    <div class="form-group">

    <label for="exampleInputEmail1">圖檔</label>

        <div>

           <div class="row">

      <label for="fileToUpload">選擇多個檔案上傳</label><br />

      <input type="file" name="fileToUpload" id="fileToUpload" οnchange="fileSelected();"  multiple="multiple"/>

    </div>     

            <ul ><li id="myimageli" ></li></ul>

            <asp:Label ID="imageLabel" runat="server" ></asp:Label>

      </div>

        <p class="help-block">允許上傳JPG,PNG,GIF格式,最佳大小:寬500,高不限制    </p>

       <div class="form-group">

    <label for="exampleInputPassword1">文字說明</label>  

      <asp:TextBox ID="body" class="form-control" style="height:90px;" TextMode="MultiLine"  runat="server"></asp:TextBox>

             </div>

            </div>

  <div class="form-group">

    <label for="exampleInputFile">釋出時間</label> 

      <asp:TextBox ID="updatedate"  class="form-control" runat="server" οnfοcus="new WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" ></asp:TextBox>

        <p class="help-block">該時間段後前台才會顯示</p>

  </div>

  <div class="checkbox">

      <label>

      <asp:CheckBox ID="isshow" Text="是否顯示"  Checked="true" runat="server" />

          </label>

  </div>

    <a href="javascript:void(0)" target="_blank" rel="external nofollow" class="btn btn-primary " id="btnadd" >

        <asp:Literal ID="lita"   runat="server"></asp:Literal>

        <i class="glyphicon glyphicon-plus"></i>

        新增 

    </a>

    <asp:HiddenField ID="hfid" Value="0" runat="server" />

</asp:Content>

js代碼

<script type="text/javascript">

           //新增按鈕發送給背景

            $(function () {

                $("#btnadd").click(function () {

                    var files = document.getElementById('fileToUpload').files;//圖檔檔案

                    var action ="add";//action表示執行動作是添加還是編輯!(通過單個上傳改的沒有去掉)

                    var updatedate = $('#<%=updatedate.ClientID%>').val();//擷取到上傳時間

                    var body = editor1.html();//擷取的說明

                    var img= $('#<%=imageLabel.ClientID%>').val();//圖檔的名稱,我把他儲存在label裡

                    var isshow = $('#<%=isshow.ClientID%>').prop("checked") ? 1 : 0;//是否顯示

                    //if (updatedate == "" || body == "" || img == "") {

                    //    layer.msg('圖檔,描述,釋出時間不能為空!')

                    //    return;

                    //}

                    var url = "moreadd.ashx";

                    var postdata = {

                        action: action,

                        id: 0,

                        updatedate: encodeURIComponent(updatedate),

                        body: encodeURIComponent(body),

                        img: img,

                        isshow: isshow

                    };

                    $.ajax({

                        url: url,

                        dataType: 'json',

                        type: "POST",

                        data: postdata,

                        success: function (json) {

                            if (json.status=="ok") {

                                location.href = "newslist.aspx";

                            } else {

                                layer.msg(json.info);

                            }

                        }

                    });

                });

            }) 

           //圖檔選擇事件判斷大小

        function fileSelected() {

            var files = document.getElementById('fileToUpload').files;

            for (var i = 0; i < files.length; i++) {

                var file = files[i];

                if (file) {

                    var fileSize = 0;

                    if (file.size > 1024 * 1024)

                        fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';

                    else

                    fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

                }

            }

            uploadFile();

        }

          // 上傳檔案事件

        function uploadFile() {

            var files = document.getElementById('fileToUpload').files;

            for (var i = 0; i < files.length; i++) {

                var file = files[i];

                if (!file) { continue; }

                var fd = new FormData();

                fd.append("fileToUpload", file);

                var xhr = new XMLHttpRequest();

               // xhr.upload.addEventListener("progress", uploadProgress, false);

                xhr.addEventListener("load", uploadComplete, false);//傳回加載

                xhr.addEventListener("error", uploadFailed, false);//出錯

                xhr.addEventListener("abort", uploadCanceled, false);//

                xhr.open("POST", "/handler/h5_upload.ashx");//post到ashx頁面

                xhr.send(fd);

            }

        }

           //上傳過程中的進度

            function uploadProgress(evt) {

            if (evt.lengthComputable) {

                var percentComplete = Math.round(evt.loaded * 100 / evt.total);

                document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';

            }

            else {

                document.getElementById('progressNumber').innerHTML = 'unable to compute';

            }

        }

           //上傳成功回調事件

        function uploadComplete(evt) {

            layer.msg('上傳成功!');

            $('#<%=imageLabel.ClientID%>').val($('#<%=imageLabel.ClientID%>').val() + evt.target.responseText + ",");//儲存多張圖檔的路徑名稱

            $('#myimageli').append('<img style="max-width:200px" src=" '+ evt.target.responseText+'"/>');//上傳之後給在頁面預覽

        }

        function uploadFailed(evt) {

            alert("There was an error attempting to upload the file.");

        }

        function uploadCanceled(evt) {

            alert("The upload has been canceled by the user or the browser dropped the connection.");

        }

    </script>

新增按鈕給背景傳位址,然後儲存到資料庫就可以完成一些列的管理.這是頁面上的一些處理如果要在背景管理可以添加一個新的頁面來做背景管理和寫一個ashx檔案來接收ajax然後處理資料..

背景接收到的資料通過string img = context.Server.UrlDecode(context.Request["img"]);

 string[] image= img.Split(',');

            for (int i = 0; i < image.Length-1; i++)

            {

//儲存到資料庫

}

來處理圖檔資訊,然後一張一張的儲存到資料庫就可以了

繼續閱讀