• 文件上传


    <body>
        <form id="form1" runat="server">
            <div>
                <asp:FileUpload ID="FileUpload1" runat="server" /><!--上传文件的控件-->
                <asp:Button ID="Button1" runat="server" Text="上传" />
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </div>
        </form>
    </body>
    </html>
    问题4:文件过大

      办法1、扩容

      Web.config配置文件:
        <httpRuntime maxRequestLength="40960"/>
        以KB为单位,默认4096,不要太大,因为会占用服务器内存

      办法2、文件大小限制
      1、C#端限制
        if (FileUpload1.PostedFile.ContentLength > (4096 * 1024))  但是,不好用

      2、客户端JS限制
        fl.files[0].size 能获取到选中文件的大小,B为单位


    <script type="text/javascript"> document.getElementById("Button1").onclick = function () { var fl = document.getElementById("FileUpload1"); if (fl.files[0].size > (1024 * 1024 * 4)) { alert("文件超过4MB"); return false; } }; 问题3:上传文件格式限制 使用JS,获取用户选择文件的后缀名,验证是否与要求的一致 //document.getElementById("Button1").onclick = function () { // var fl = document.getElementById("FileUpload1"); // var aa = fl.value.substr(fl.value.length - 4, 4); // if (aa != ".txt" && aa != ".png" && aa != ".jpg") { // alert("文件格式选择不正确!"); // return false; // } //}; </script>

    1、将目标文件传到目标路径下

    先将项目中的相对路径位置写出来
    string path = "images/aaa.txt";

    将此相对路径映射成绝对路径
    string endpath = Server.MapPath(path);

    记住FileUpload1.SaveAs("保存的绝对路径");

      protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += Button1_Click;
        }
    
        void Button1_Click(object sender, EventArgs e)
        {

          问题1:文件重名,切容易被覆盖

          办法:保留文件原有的名字

    
    

         问题2:文件重名,多人上传同一名称的文件会被覆盖

               名称添加时间拼接,用户名拼接

    string path = "images/" + DateTime.Now.ToString("yyyyMMddhhmmss") +Request.Cookies["User"].Value+ FileUpload1.FileName;
            string endpath = Server.MapPath(path);
    
            if (FileUpload1.PostedFile.ContentLength > (4096 * 1024))
            {
                Label1.Text = "文件超过4MB";
            }
            else
            {
                FileUpload1.SaveAs(endpath);保存
            }
    
    
        }
  • 相关阅读:
    【CodeForces 438D 】The Child and Sequence
    【雅礼集训 2017 Day1】市场
    【POJ2528】Mayor's posters
    【NOIP模拟】图论题Graph
    【BZOJ2654】Tree
    【NOIP模拟】函数
    【NOIP模拟】箱子
    【CQOI2014】数三角形
    【USACO2009Feb】股票市场
    【APIO2009-3】抢掠计划
  • 原文地址:https://www.cnblogs.com/yp11/p/5966228.html
Copyright © 2020-2023  润新知