008. 限制上传文件的大小

第一种方法:

利用web.config的配置文件项, 进行设置;

前端aspx示例:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sendOutEmail.aspx.cs" Inherits="sendOutEmail" %>
<!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 >
    <title>文件上传</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <table >
         <tr>
             <td ><asp:FileUpload ID="FileUp" runat="server"  Width="456px" style="border: 1px solid red" Height="21px"/></td>
         </tr>
         <tr>
             <td>
                <asp:Button ID="BtnSend" runat="server"  OnClick="ImgBtnSend_Click" Text="提交" />&nbsp;<asp:Button ID="Btnchongzhi" runat="server" Text="重置"  CausesValidation="False" onclick="Btnchongzhi_Click" />
                <asp:Label ID="LblMessage" runat="server" ForeColor="Red" Width="88px" />
              </td>
              </tr>
        </table>
    </div>
    </form>
</body>
</html>

后端cs文件的部分内容:

 protected void ImgBtnSend_Click(object sender, EventArgs e)
    {
        string filepath = FileUp.PostedFile.FileName; //获取客户端上传文件的文件的路径,即FileUpload控件文本框中的所有内容
        //FileUp.FileName 只获取上传文件的文件名
        string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
        string serverpath = Server.MapPath("~/") + filename; //返回服务器上与指定虚拟路径对应的物理路径
        FileUp.PostedFile.SaveAs(serverpath);//将文件保存到服务器上
        LblMessage.Text = "恭喜您!文件上传成功!";
    }

web.config文件中的部分内容

 <system.web>
<!--设置上传文件的最大 大小 为4M, 超时时间为100秒-->
    <httpRuntime maxRequestLength="4096" executionTimeout="100"/> 
</system.web>

第二种方法: 通过编程的形式限制上传文件的大小, 这里将其显示为1MB为例;前端代码不变, 后端稍加修改

 protected void Button1_Click(object sender, EventArgs e)
    {

        //获取客户端上传文件的文件的路径,即FileUpload控件文本框中的所有内容
        string filepath = FileUp.PostedFile.FileName;
        //FileUp.FileName 只获取上传文件的文件名
        string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
        if (FileUp.PostedFile.ContentLength > 1024000)
        {
            LblMessage.Text = "文件大小不能超过1MB!";
        }
        else
        {
            //返回服务器上与指定虚拟路径对应的物理路径
            string serverpath = Server.MapPath("~/") + filename;
            FileUp.PostedFile.SaveAs(serverpath);
            LblMessage.Text = "恭喜您!文件上传成功!";
        }
    }

注: 上传文件时, 有时浏览器会报如下错误, 没有关系, 清空下缓存或者换个浏览器就好了

posted on 2016-11-07 16:55  印子  阅读(176)  评论(0编辑  收藏  举报

导航