1. 程式人生 > >檔案上傳控制元件Fileupload(實現檔案上傳並寫入資料庫)

檔案上傳控制元件Fileupload(實現檔案上傳並寫入資料庫)

首先我們來說一下Fileupload這個檔案上傳控制元件的幾大敗筆:

1.上傳之後按F5重新整理,重複提交

2.提交以後按後退鍵Fileupload中的資訊還在

3.不支援多檔案上傳

4.上傳前不能檢測檔案大小

解決方法:

1.建立iframe在子頁面實現或者重定向語句(Response.Redirect(Request.RawUrl);)

2.用JavaScript語句將fileupload中的val資訊清空

4.利用js程式碼:fileupload.files[0].size程式碼解決,但需要瀏覽器支援html5

另外,需要強調的是如果要更改預設上傳檔案的最大值以及上傳時間需要去web.config檔案去修改

 <httpRuntime maxRequestLength="8192" executionTimeout="90"/>

下面是利用iframe實現檔案上傳並寫入資料庫的例程:

iframe.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="iframe_upload.aspx.cs" Inherits="uploadfiles_iframe_upload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>upload上傳檔案儲存到資料庫</h2>
    <iframe frameborder="0" width="100%" src="i_upload.aspx"></iframe>
    </div>
    </form>
</body>
</html>
i_upload.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="i_upload.aspx.cs" Inherits="uploadfiles_iframe_upload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="../jquery-1.11.3.min.js" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#fup1").val(""); //將fileupload中的val資訊清空
        });

        function checkdata() {
            if ($("#fup1").val() == "") {
                alert("請選擇檔案");
                $("#fup1").focus(); //將焦點定在fileupload控制元件上
                return false;
            }

            var _file = document.getElementById("fup1"); //尋找頁面中特定ID值的控制元件
            var _size = _file.files[0].size; //在提交之前提取檔案的大小

            if (_size > 4000000) {
                alert("檔案過大");
                $("#fup1").focus();
                return false;
            }

            return true;
         }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:FileUpload ID="fup1" runat="server" />
        
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="return checkdata()" />
        
    </div>
    </form>
</body>
</html>

i_upload.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class uploadfiles_iframe_upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session["_tempFiles"] = fup1.PostedFile; //將資訊寫入session
        Response.Redirect("i_info.aspx"); //轉到i_info頁面
    }
}


i_info.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="i_info.aspx.cs" Inherits="uploadfiles_iframe_upload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    title:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    fc_id:<asp:Label ID="lb_fcid" runat="server" Text="Label"></asp:Label><br/>
    fc_name:<asp:Label ID="lb_fcname" runat="server" Text="Label"></asp:Label><br/>
    targDir:<asp:Label ID="lb_tdir" runat="server" Text="Label"></asp:Label><br/>
    targPath:<asp:Label ID="lb_fcpath" runat="server" Text="Label"></asp:Label><br />
    </div>
    <asp:Button ID="Button1" runat="server" Text="儲存" onclick="Button1_Click" />
    </form>
</body>
</html>

i_info.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;

public partial class uploadfiles_iframe_upload : System.Web.UI.Page
{

    string str_cnn = "Provider=MicroSoft.Jet.OLEDB.4.0;Data Source=";
    string str_sourcefile = "~/uploadfiles/data.mdb";
    OleDbCommand cmd;
    OleDbConnection cnn;
    OleDbDataReader deter;
    string str_sql;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["_tempFiles"] == null)
        {
            Response.Redirect("i_upload.aspx");
        }
        HttpPostedFile _myfiles = (HttpPostedFile)Session["_tempFiles"]; //讀取session,存入_myfiles中
        string _ext = Path.GetExtension(_myfiles.FileName).ToLower(); //獲取檔案的副檔名,並轉化為小寫


        string str_conn = str_cnn + MapPath(str_sourcefile);
        cnn = new OleDbConnection(str_conn);

        cnn.Open();
        //設定預設值
        lb_fcid.Text = "1";  
        lb_fcname.Text = "其他";
        lb_tdir.Text = "~/uploadfiles/其他";

        str_sql = "SELECT * FROM T_FILE WHERE fc_ext like '%" + _ext + "%'";//注意變數值的分離方法
        cmd = new OleDbCommand(str_sql, cnn);
        deter = cmd.ExecuteReader();
<span style="white-space:pre">	</span>//讀資料庫
        while (deter.Read())
        {
            lb_fcid.Text = deter["ID"].ToString();
            lb_fcname.Text = deter["fc_name"].ToString();
            lb_tdir.Text = deter["fc_path"].ToString();
        }

        TextBox1.Text = _myfiles.FileName.ToString();
        lb_fcpath.Text = MapPath(lb_tdir.Text) + DateTime.Now.ToOADate() + _ext; //構建檔案路徑

        cnn.Close();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string _targPath = lb_fcpath.Text;
        string _targDir = lb_tdir.Text;

        try 
        {
            Directory.CreateDirectory(MapPath(_targDir)); //檢查有無檔案目錄,如果沒有則建立
            ((HttpPostedFile)Session["_tempfiles"]).SaveAs(_targPath);//存檔案

        }
        catch { }

        if (File.Exists(_targPath)) 
        {
            string _fname, _fcid, _title;
            _fname = Path.GetFileName(lb_fcpath.Text);
            _fcid = lb_fcid.Text;
            _title = TextBox1.Text;

        string str_conn = str_cnn + MapPath(str_sourcefile);
        cnn = new OleDbConnection(str_conn);

        cnn.Open();
<span style="white-space:pre">	</span>//存入資料庫
        str_sql = "INSERT INTO T_FILEINFO(f_name,f_path) values "+"('"+_fname+"','"+_title+"')";
        cmd = new OleDbCommand(str_sql, cnn);
        int i = cmd.ExecuteNonQuery();
        cnn.Close();

        if (i > 0) 
        {
            Session.Remove("_tempfiles");//清除session
            Response.Redirect("i_down.aspx");
        }
        }
    }
}

i_down.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="i_down.aspx.cs" Inherits="uploadfiles_iframe_upload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <p>上傳成功</p>
        <p>
            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/uploadfiles/i_upload.aspx">再次上傳</asp:HyperLink>
        </p>
    
    </div>
    </form>
</body>
</html>