自动上载文件

时间:2022-02-11 06:01:58

      UploadPage.aspx

    <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
           <iframe id="file" frameborder="0" marginheight="0" marginwidth="0" src="UploadFileFramePage.aspx"></iframe>
        </ContentTemplate>
        </asp:UpdatePanel>

 

UploadFileFramePage.aspx

<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:FileUpload ID="fuFile" runat="server" />
        <asp:Label ID="lbMessage" runat="server" ForeColor="Blue"></asp:Label>
        <asp:Timer ID="tCount" runat="server" Interval="5000" OnTick="tCount_Tick">
        </asp:Timer>

 

 protected void tCount_Tick(object sender, EventArgs e)
    {
        if (fuFile.HasFile == true)
        {
            UploadFile(fuFile);
        }
    }
    private bool UploadFile(FileUpload fu)
    {
        if (fu.HasFile == false)
        {
            lbMessage.Text = "上载文件为空,请重新选择上载的文件...";
            lbMessage.Visible = true;
            return false;
        }
        if (fu.PostedFile.ContentLength <= 0)
        {
            lbMessage.Text = "上载文件的大小为空,请重新选择上载的文件...";
            lbMessage.Visible = true;
            return false;
        }

        DateTime dt = DateTime.Now;
        string fileName = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + dt.Millisecond.ToString();
        fileName += fu.FileName.Substring(fu.FileName.LastIndexOf("."));
        fileName = "Files/" + fileName;

        string fullName = Server.MapPath(fileName);
        if (System.IO.File.Exists(fullName) == true)
        {
            lbMessage.Text = "上载文件已经存在,请重新上载....";
            lbMessage.Visible = true;
            return false;
        }
        try
        {
            fu.SaveAs(fullName);
        }
        catch (Exception ex)
        {
            lbMessage.Text = "上载文件失败,失败原因为:" + ex.Message;
            lbMessage.Visible = true;
            return false;
        }
        lbMessage.Text = "上载文件成功,请妥善保管你的文件.";
        lbMessage.Visible = true;
        return true;
    }