zoukankan      html  css  js  c++  java
  • asp.net+bootstrap上传图片+FileUpload控件文件上传下载

    ps:我数据库使用的pgsql,看个人修改。

    代码asp.net 的,使用了mootools框架,里面包含了bootstrap上传图片,查看预览,还加了个上传任意文件的FileUpload。(界面随便弄的)

    没有mootools的,自己去下

    下载那里貌似有点小问题,如有啥问题,欢迎留言~~

    前台代码部分:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="file_up.aspx.cs" Inherits="file_up" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <link rel="stylesheet" href="css/BootstrapCSS/bootstrap.css"/>
        <link rel="stylesheet" type="text/css" href="/css/ShouYe/style.css" />
        <script type="text/javascript" src="js/jquery.3.2.1.js"></script>
        <script src="js/BootstrapJS/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="map7api/mootools-core-1.4.1-full-compat.js" type="text/javascript" charset="utf-8"></script>
    
        <script src="js/BootstrapJS/fileinputJS/fileinput.js"></script>
        <link rel="stylesheet" href="css/BootstrapCSS/fileinputCSS/fileinput.min.css" />
        <script src="js/BootstrapJS/bootstrap3-dialog/bootstrap-dialog.js"></script>
        <link rel="stylesheet" href="css/BootstrapCSS/bootstrap3-dialogCss/bootstrap-dialog.css" />
    
        
        <link rel="stylesheet" href="js/js_image/jquery.mmenu.all.css" />
        <link rel="stylesheet" href="js/js_image/slick.css" />
        <link rel="stylesheet" href="js/js_image/reset.css" />
        <link href="js/js_image/viewer.css" rel="stylesheet" />
        
        <script src="js/js_image/viewer.js" type="text/javascript" charset="utf-8"></script>
        <script src="js/js_image/main.js" type="text/javascript" charset="utf-8"></script>
        
        <title>文件上传</title>
    
        
    <style>
            .nav_left li{
                list-style-type:none;
            }
    
            .div_property{
                margin: 10px 0px;
            }
    
            #div_page{ 
                 margin:0 auto;
                 text-align:center;
                 200px;
             }
            #div_page li { 
                list-style:none; /* 将默认的列表符号去掉 */
            float:left; /* 往左浮动 */
            margin:10px 10px;
            padding:2px 5px;
                background-color:#f8f8f8;
                border:1px solid #e8e8e8;
            }
            #div_page  .active{
                padding:2px 5px;
                background-color:#4c9ed9;
                border:1px solid #e8e8e8;
            }
            #div_page  .active a{ 
                color:#fff;
            }
    
            #div_btn {
                /*float:right;*/
                display:none;
                position:fixed;right:0px;top:200px;
            }
            #div_btn img{
                30px;
            }
        </style>
    </head>
    <body>
            <form id="form1" runat="server">
            <div style="height:200px; 1000px; margin:0 auto; text-align:center;">
                           <div style=" margin-top:50px;">
                          <p style="font-size:24px">上传图片</p></br>
                          <input class="btn btn-success" type="button" data-toggle="modal" data-target="#myModal" data-id='1' value="添加" />
                          <input class="btn btn-success" type="button" data-toggle="modal" data-target="#myModal" data-id='2' value="修改" />
                          <input class="btn btn-success" type="button"  value="删除" onclick="del();" />
                           </div>
                   </div>
                <hr />
                <div style="margin-top:20px; margin:0 auto;" >
                    <p style="font-size:24px;text-align:center;">上传文件</p></br>
                    <div style="margin-left:420px;">
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                    <asp:Button ID="Button1" runat="server" Text="上传" OnClick="Button1_Click" />
                      <asp:Button ID="Button2" runat="server" Text="下载" OnClick="Button2_Click" /><br />
                       <!-- <asp:ListBox ID="lb_FileList" runat="server" AutoPostBack="True" Width="300px" Height="300px"  OnSelectedIndexChanged="lb_FileList_SelectedIndexChanged">
                            <asp:ListItem Value="文件列表:"></asp:ListItem>
                        </asp:ListBox> <br />-->
                        <asp:GridView ID="GridView1" runat="server" Width="700px" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
                            <AlternatingRowStyle BackColor="White" />
                            <Columns>
                                <asp:BoundField DataField="fileid" HeaderText="fileid" />
                                <asp:BoundField DataField="filename" HeaderText="文件名称" />
                                <asp:BoundField DataField="filelength" HeaderText="文件大小" />
                                <asp:BoundField DataField="filetype" HeaderText="文件类型" />
                                 <asp:TemplateField HeaderText="资源下载" >
                  <ItemTemplate>
                     <asp:LinkButton ID="lbtnDown" runat="server"  OnCommand="lbtnDown_Click" CommandArgument='<%#Eval("filepath").ToString() %>'>下   载</asp:LinkButton>
                  </ItemTemplate>
                  </asp:TemplateField>
                            </Columns>
                            <EditRowStyle BackColor="#2461BF" />
                            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                            <RowStyle BackColor="#EFF3FB" />
                            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                            <SortedAscendingCellStyle BackColor="#F5F7FB" />
                            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                            <SortedDescendingCellStyle BackColor="#E9EBEF" />
                            <SortedDescendingHeaderStyle BackColor="#4870BE" />
                        </asp:GridView></br>
                        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                        <asp:Label ID="lab_FileDescription" runat="server" Text=""></asp:Label>     
                    </div>
                </div>
                </form>
             
                
                <div id="div_moreInfo">
                    <ul class="honor_ul clearfix" id="ul_proList" style="list-style:none;">
                       
                    
                    </ul> 
                    </div>
                    <div id="div_page"></div>
                  <div>
                         <input id="input_page" style="25px;margin-left:50px;"/>
                         <a href="javascript:#" onclick="changePage(limit, limitPage, document.getElementById('input_page').value, total);" >跳转</a>
                    </div>
        <!-- 模态框(Modal) -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            &times;</button>
                        <h4 class="modal-title" id="myModalLabel">
                            添加
                        </h4>
                    </div>
                    <div class="modal-body div_property">
    
    
                        <input id="f_upload" name="input2" type="file" class="file" multiple
                               data-show-upload="false" data-show-caption="true" data-show-preview="true" data-allowed-file-extensions='["jpg","png"]'>
    
    
    
                        <div class="input-group div_property">
                            <span class="input-group-addon">名称</span>
                            <input id="input_name" type="text" class="form-control" placeholder="twitterhandle">
                        </div>
                        <div class="form-group div_property">
                            <label for="name">描述</label>
                            <textarea id="textarea_description" class="form-control" rows="5"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">
                            关闭
                        </button>
                        <button type="button" class="btn btn-primary" onclick="submit();">
                            提交
                        </button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal -->
        </div>
    
    
           
    </body>
    </html>
    View Code

    运行界面:

    后台代码部分:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Npgsql;
    using System.Data;
    using System.IO;
    using FrameWork;
    using System.Configuration;
    public partial class file_up : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
            {
                if(!IsPostBack){
                    init();
                }
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                if(FileUpload1.PostedFile.FileName==string.Empty){
                    Response.Write("<script>alert('请选择要上传的文件!');</script>");
                }
                else
                {  //获取要上传的文件的信息
                    //获取要上传的文件的信息
                    string filepath = FileUpload1.PostedFile.FileName;//文件路径
                    string oldfilename = filepath.Substring(filepath.LastIndexOf("/") + 1);//文件名
                    string FileExtension = Path.GetExtension(oldfilename); //文件的扩展名
                    int filelength = (int)oldfilename.Length;//文件名长度
                    //随机生成文件名
                    Random Rnd = new Random();
                    int strRnd = Rnd.Next(1, 99);
                    string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + strRnd.ToString() + FileExtension.ToLower();
                    //将文件上传到以当前日期命名的文件夹中
                    string UpLoadName = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();
                    bool FileUploadPathExists = File.Exists(Server.MapPath("UpLoad" + "/" + UpLoadName));
                    //指定文件夹不存在,如果不存在就创建该文件夹
                    if (!FileUploadPathExists)
                    {
                        Directory.CreateDirectory(Server.MapPath("UpLoad" + "/" + UpLoadName));
                    }
                    //保存上传的文件
                    string savapath = Server.MapPath("UpLoad" + "/" + UpLoadName);//保存路径
                    string savapath1 = "UpLoad" + "/" + UpLoadName + "/" + newfilename;//保存路径
                    FileUpload1.PostedFile.SaveAs(savapath + "/" + newfilename);
                    
                    //连接数据库字符串
                    string connectionString1 = "Server=localhost; Port=5432;Database=city;User ID=postgres;Password=postgres";
                    NpgsqlConnection conn = new NpgsqlConnection(connectionString1);
                    conn.Open();
                    //conn.Close();
                    string sql = "insert into u_file(FileName,FileLength,FileType,FilePath) values('" + newfilename + "','" + filelength + "','" + FileExtension + "','" + savapath1 + "')";
                    //conn.Open();
                    NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);            
    
                    try
                    {
                       
                        //int count = Convert.ToInt32(cmd.ExecuteScalar());
                       // string.Format Response.Write("<script>alert('连接成功')</script>");
                        cmd.ExecuteNonQuery();
                        //刷新页面
                        Response.AddHeader("Refresh", "0"); 
    
                        //显示信息
                            //NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql,connectionString1);
                            //System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
                            //strMsg.Append("<font color=green>文件被成功添加到数据库中,详细信息如下所示:<br>");
                            //strMsg.Append("上传的文件的类型为:" + this.FileUpload1.PostedFile.ContentType.ToString() + "<br>");
                            //strMsg.Append("客户端文件的地址为:" + filepath + "<br>");
                            //strMsg.Append("上传文件的文件名为:" + newfilename + "<br>");
                            //strMsg.Append("文件上传到服务器的路径为:" + savapath + "<br>");
                            //strMsg.Append("上传文件的扩展名为:" + FileExtension + "<br>");
                            //strMsg.Append("上传文件的大小为:" + FileUpload1.PostedFile.ContentLength + "个字节</font>");
                            //this.Label1.Text = strMsg.ToString();
                        
                    }
                    catch (Exception error)
                    {
                        Response.Write(error.ToString());
                    }
                    finally
                    {
                        conn.Close();
                    }
                   
                
                }
            }
    
            private void init() {
    
                //连接数据库字符串
                string connectionString1 = "Server=localhost; Port=5432;Database=city;User ID=postgres;Password=postgres";
                NpgsqlConnection conn = new NpgsqlConnection(connectionString1);
                conn.Open();
                //conn.Close();
                string sql = "select fileid,filename,filelength,filetype,filepath from u_file";
                //conn.Open();
                NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds,"table");
                this.GridView1.DataSource = ds;
                this.GridView1.DataBind();
                //NpgsqlDataReader dr = cmd.ExecuteReader();
               /* while(dr.Read()){
    
                    this.lb_FileList.Items.Add(new ListItem(dr.GetString(1), dr.GetInt32(0).ToString()));
                }*/
                //dr.Close();
                conn.Close();
    
            }
    
            //下载
            protected void lbtnDown_Click(Object sender, CommandEventArgs e){
            
                // 定义文件路径
                string url = "";
                // 定义文件名
                string fileName = "";
     
                // 获取文件在服务器的地址
                url = e.CommandArgument.ToString();
                //Response.Write(e.CommandArgument.ToString());
     
     
                // 取得地址中的文件名
                // 判断传输地址是否为空
                if (url == "")
                {
                // 提示“该文件暂不提供下载”
               // Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script defer>alert('该文件暂不提供下载!');</script>");
                    Response.Write("<script>alert('该文件暂不提供下载!')</script>");
                return;
            }
     
                // 判断获取的是否为地址,而非文件名
                if (url.IndexOf("/") > -1)
                {
                    // 获取文件名
                    fileName = url.Substring(url.LastIndexOf("/") + 1);//获取文件名
     
                }
                else
                {
                    // url为文件名时,直接获取文件名
                    fileName = url;
                }
     
                // 流方式下载文件 
     
                try
                {
                    // 定义服务器路径
                    string urlServer = Server.MapPath(url);
     
                    // 以字符流的方式下载文件
                    FileStream fileStream = new FileStream(urlServer, FileMode.Open);
                    byte[] bytes = new byte[(int)fileStream.Length];
                    fileStream.Read(bytes, 0, bytes.Length);
                    fileStream.Close();
                    Response.ContentType = "application/octet-stream";
     
                    // 通知浏览器下载而不是打开
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                    Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();
                }
                catch (Exception)
                {
            
                }
    
            }
            protected void lb_FileList_SelectedIndexChanged(object sender, EventArgs e)
            {
                //从config中读取文件上传路径
                //string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
                //从列表框控件中读取选择的文件名 
                //string strFileName = lb_FileList.SelectedValue; 
                //组合成物理路径       
                //string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName); 
                //根据物理路径实例化文件信息类   
                //FileInfo fi = new FileInfo(strFilePhysicalPath);
                //获得文件大小和创建时间并赋值给标签  
                //lab_FileDescription.Text = string.Format("文件大小:{0} 字节<br><br>上传时间:{1}<br>", fi.Length, fi.CreationTime); 
                //把文件名赋值给重命名文本框     
                //tb_FileNewName.Text = strFileName;  
            }
            protected void Button2_Click(object sender, EventArgs e)
            {
               Response.Write("<script>alert('点个锤子!')</script>");
             
            }
    
           
    }
    View Code

    下载界面:

    关于

    做得不好,希望有用。

  • 相关阅读:
    例题6-8 Tree Uva548
    例题6-7 Trees on the level ,Uva122
    caffe Mac 安装
    Codeforces Round #467 (Div. 1) B. Sleepy Game
    Educational Codeforces Round37 E
    Educational Codeforces Round 36 (Rated for Div. 2) E. Physical Education Lessons
    Good Bye 2017 E. New Year and Entity Enumeration
    Good Bye 2017 D. New Year and Arbitrary Arrangement
    Codeforces Round #454 D. Seating of Students
    浙大紫金港两日游
  • 原文地址:https://www.cnblogs.com/maoye520/p/11510923.html
Copyright © 2011-2022 走看看