zoukankan      html  css  js  c++  java
  • 文件上传

    <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);保存
            }
    
    
        }
  • 相关阅读:
    .请写出常用的linux指令
    Maven常用命令有哪些
    Maven的工程类型有哪些
    eclipse中Build Path 导入的包和复制到 lib 包的区别
    马踏棋盘算法递归+回溯法实现 C语言
    微信开发之移动手机WEB页面(HTML5)Javascript实现一键拨号及短信发送功能
    Android_保存用户名和密码码sharedPreference
    Android---XML序列化
    直接拿来用!最火的Android开源项目
    异步http开源框架使用(AsyncHttpClient)
  • 原文地址:https://www.cnblogs.com/yp11/p/5966228.html
Copyright © 2011-2022 走看看