我的编程笔记-asp.net批量上传图片

来源:互联网 发布:淘宝店运营计划书 编辑:程序博客网 时间:2024/04/30 14:23

前几天做了批量上传图片的功能,看似简单,其实也不简单,主要还是细节!

先看图


文字说明的textbox经过了处理然后支持了工具栏

<script src="../Content/My97DatePicker/WdatePicker.js"></script>
     <link href="../Content/kindeditor/themes/qq/qq.css" 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" onchange="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" onfocus="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)" 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++)
            {

//保存到数据库

}

来处理图片信息,然后一张一张的保存到数据库就可以了

1 0
原创粉丝点击