用自定义上传控件实现上传功能

本文介绍了一种通过异步调用实现简单文件上传功能的方法,并提供了详细代码实现,包括上传文件限制、文件类型验证及文件保存逻辑。同时,展示了如何通过隐藏页面和JavaScript进行交互,以实现实时反馈和简化用户界面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    由于vs自带的上传控件样式修改不方便,所以我在这里用一个很简单的方法来实现上传功能,如果有高手能提供上传时显示进度条的代码就更好了。效果如图所示:

 

实现方式是通过异步调用来实现的,首先准备一个调用的隐藏页面,界面代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadFile.aspx.cs" Inherits="Travelling.UploadFile" %>

<!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>
<script language="jscript">
function Testgetparent()
{
    parent.document.getElementById('ctl00_mainContentPlaceHolder_ButtonHidden').click();
    return false;
}

</script>
<body style="margin:0px">
    <form id="form1" runat="server">
    <div>
   
        <asp:FileUpload ID="FileLoader" runat="server" Width="380px" />
        <asp:Button ID="ButtonUpload" runat="server" Text="Button"
            onclick="ButtonUpload_Click" />
    </div>
    </form>
</body>
</html>


C#后台代码如下:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

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


        }

        protected void ButtonUpload_Click(object sender, EventArgs e)
        {

                 FileUpload();
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        private void FileUpload()
        {

            if (FileLoader.FileContent.Length > 5242880)
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('This file is too large,please upload the file is less than 5M.');</script>");
                return false;
            }

            //验证文件是否存在
            if (FileLoader.PostedFile.FileName != "")
            {
                string filePath = FileLoader.PostedFile.FileName;//客户端文件路径
                FileInfo file = new FileInfo(filePath);
                //获取文件类型
                string fileContentType = file.Extension.ToUpper();
                string[] canNotUploadFileType = System.Configuration.ConfigurationManager.AppSettings["CanNotUploadFileType"].Split(',');
                if (canNotUploadFileType.Contains(fileContentType))
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('Upload failed!Type is incorrect.');</script>");
                    return false;
                }//if (fileContentType == "application/octet-stream")
                string ServerFilePath = Server.MapPath("Upload/" + file.Name);// 服务器端文件路径
                if (!File.Exists(ServerFilePath))
                {
                    try
                    {
                        //string ServerFilePath = Server.MapPath(stringPath[i].Substring(2));
                        FileLoader.SaveAs(ServerFilePath);// 使用 SaveAs 方法保存文件
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }//if (!File.Exists(webFilePath))
            }//
            return true;
        }

    }
}

 

 

调用页面的界面代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="FileUpload" %>

<!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>FileUpload</title>
</head>

<script type="text/javascript" language="javascript">

function ShowBrowser(frameID)
{
    window.event.cancelBubble = true;
    window.event.returnValue = false;
    var fra = document.frames(frameID);
//    alert(fra);
    var uploadForm = fra.document.forms['testframe'];
//    alert(!uploadForm)
    if (!uploadForm) {
        uploadForm = fra.document.form1;
    }
//    uploadForm.FileLoader.click();
    try
    {
        if (uploadForm.FileLoader != null && typeof (uploadForm.FileLoader) != 'undefined' && uploadForm.ButtonUpload != null && typeof (uploadForm.ButtonUpload) != 'undefined')
        {
            uploadForm.FileLoader.click();
            if (uploadForm.FileLoader.value.length > 0)
            {
             
                uploadForm.ButtonUpload.click();
               
            }
        }

    }
    catch (ex) {
    alert(ex)

    }
    //return false;
}

</script>

<body>

     <form id="form1" runat="server">
           <div>

                  <table>
                         <tr>
                         <td>
                          <iframe style="height:20px;width:100px; display:none;"  frameborder="no" scrolling="no" src="UploadFile.aspx" id="testframe"></iframe>
                        <asp:ImageButton ID="ButtonUpload" ImageUrl="~/image/Upload.gif"
                            runat="server" OnClientClick="ShowBrowser('testframe');" ToolTip="Upload" />
                         <asp:Button ID="ButtonHidden" runat="server"
                         onclick="ButtonUpload_Click" style="display:none;"/>
                         </td>
                         <td>
                             <asp:DataList ID="DataListFile" runat="server" RepeatColumns="6"
                                 RepeatDirection="Horizontal" onitemcommand="DataListFile_ItemCommand"
                                 onitemdatabound="DataListFile_ItemDataBound">
                             <ItemTemplate>
                             <table cellpadding="0" cellspacing="0" border="0">
                             <tr>
                             <td id="mytd" style="white-space:nowrap">
                                  <asp:ImageButton ID="ImageButtonRead" ImageUrl="~/image/icon/Attachment.gif"
                                      runat="server" ToolTip='<%#Bind("target_name")%>' CommandName="Read" CommandArgument='<%#Bind("upload_file_id") %>' onmouseover="checkEventOver(this);" />
                                      </td>
                                      <td>
                                      <div id="delbtn" style="display:none">
                            <asp:ImageButton ID="ImageButtonDelelte" ImageUrl="~/image/icon/deletefile.gif" CssClass="clear"
                                      CommandName="Del" CommandArgument='<%#Bind("upload_file_id") %>' runat="server"
                                      ToolTip="Delete" /></div>
                            </td></tr></table>
                             </ItemTemplate>
                             </asp:DataList>
                         </td>
                         </tr>
                         </table>

                  </div>
          </form>

</body>

</html>

 

C#后台代码可以根据需要自己写。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值