Junhong_c 2024-12-16 12:09 采纳率: 0%
浏览 8

C# 网页使用FileUpload1控件上传文件, 如何使用ScriptManager及UpdatePanel 读取文件后可以局部刷新使用进度条

C# 网页上传电子表格文件并读取数据内容,可以使用进度条或提示条吗?

以前使用window form可以使用进度条来显示上传文件及数据的进度,现在需要用web form来替换window form来实现上传文件及更新数据的进度。

使用ScriptManager及UpdatePanel 可以局部刷新使用进度条,但却无法同时获取要上传文件的文件名,FileUpload1 控件可能是要传递整页数据,造成两个控件同时使用达不到效果。 有什么办法可以得到这种效果吗?即能上传文件并读取文件数据,还能显示进度情况,让用户比较好的体验吗

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript" language="javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    function BeginRequestHandler(sender, args) {
        var elem = args.get_postBackElement();
        ActivateAlertDiv('visible', 'AlertDiv', elem.value + ' processing...');
    }
    function EndRequestHandler(sender, args) {
        ActivateAlertDiv('hidden', 'AlertDiv', '');
    }
    function ActivateAlertDiv(visstring, elem, msg) {
        var adiv = $get(elem);
        adiv.style.visibility = visstring;
        adiv.innerHTML = msg;
    }
</script>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="Server" >
<ContentTemplate>
        <asp:Button ID="Btn_Process" runat="server" Text="Upload"  Onclick="UploadClick_Handler"/>
</ContentTemplate>
<Triggers>
    <asp:PostBackTrigger ControlID="Btn_Process"   />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
    <div id="AlertDiv" class="AlertStyle"></div>
</ProgressTemplate>
</asp:UpdateProgress>
  • 写回答

1条回答 默认 最新

  • 道友老李 JWE233286一种基于机器视觉的水表指针读数识别及修正的方法 专利发明者 2024-12-16 12:13
    关注
    让【道友老李】来帮你解答,本回答参考通义千问qwen-plus编写,并整理提供,如果还有疑问可以点击头像关注,评论或留言
    要在ASP.NET Web Forms中实现文件上传并显示进度条,确实需要一些技巧,因为传统的`FileUpload`控件和`UpdatePanel`结合时会有一些限制。以下是一个解决方案,通过使用HTML5的`FormData`和`XMLHttpRequest`来实现文件上传并显示进度条。

    解决方案概述

    1. 前端部分:使用HTML5的FormData对象和XMLHttpRequest来发送文件,并在发送过程中监听进度事件。
    2. 后端部分:使用C#处理文件上传请求,并返回响应。

    前端代码

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>File Upload with Progress Bar</title>
        <style>
            #progressBar {
                width: 100%;
                background-color: #f3f3f3;
            }
            #progressBar div {
                height: 30px;
                text-align: center;
                line-height: 30px;
                color: white;
                background-color: #4caf50;
                width: 0;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <input type="file" id="fileInput" />
                <button id="uploadButton">Upload</button>
                <div id="progressBar">
                    <div id="progress"></div>
                </div>
            </div>
        </form>
    
        <script type="text/javascript">
            document.getElementById('uploadButton').addEventListener('click', function (e) {
                e.preventDefault();
    
                var fileInput = document.getElementById('fileInput');
                var file = fileInput.files[0];
                if (!file) {
                    alert('Please select a file');
                    return;
                }
    
                var formData = new FormData();
                formData.append('file', file);
    
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'UploadHandler.ashx', true);
    
                xhr.upload.onprogress = function (event) {
                    if (event.lengthComputable) {
                        var percentComplete = (event.loaded / event.total) * 100;
                        document.getElementById('progress').style.width = percentComplete + '%';
                        document.getElementById('progress').innerHTML = Math.round(percentComplete) + '%';
                    }
                };
    
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        alert('File uploaded successfully');
                    } else {
                        alert('Error uploading file');
                    }
                };
    
                xhr.send(formData);
            });
        </script>
    </body>
    </html>
    

    后端代码

    创建一个HTTP处理程序(.ashx文件)来处理文件上传请求。

    using System;
    using System.IO;
    using System.Web;
    
    public class UploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
    
            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile file = context.Request.Files[0];
                string filePath = context.Server.MapPath("~/Uploads/" + file.FileName);
    
                // Save the file
                file.SaveAs(filePath);
    
                context.Response.Write("File uploaded successfully");
            }
            else
            {
                context.Response.Write("No file uploaded");
            }
        }
    
        public bool IsReusable
        {
            get { return false; }
        }
    }
    

    说明

    1. 前端部分

      • 使用<input type="file" id="fileInput" />来选择文件。
      • 使用<button id="uploadButton">Upload</button>来触发上传操作。
      • 使用<div id="progressBar"><div id="progress"></div></div>来显示进度条。
      • JavaScript代码中,使用FormData对象来封装文件数据,并使用XMLHttpRequest对象来发送POST请求。通过监听onprogress事件来更新进度条。
    2. 后端部分

      • 创建一个HTTP处理程序(UploadHandler.ashx),在ProcessRequest方法中处理文件上传请求。
      • 将上传的文件保存到服务器上的指定目录,并返回成功或失败的响应。

    注意事项

    • 确保服务器上有足够的权限来写入文件。
    • 处理大文件时,考虑增加超时时间。
    • 可以根据需要添加更多的错误处理和日志记录。

    通过这种方式,你可以在ASP.NET Web Forms中实现文件上传并显示进度条,提供更好的用户体验。

    评论

报告相同问题?

问题事件

  • 创建了问题 12月16日