• ASP.NET(99):Cookie操作、ASP.Net文件上传HttpPostedFile


    概述

    Cookie用来保存客户浏览器请求服务器页面的请求信息。

    我们可以存放非敏感的用户信息,保存时间可以根据需要设置。如果没有设置Cookie失效日期,它的生命周期保存到关闭浏览器为止,Cookie对象的Expires属性设置为MinValue表示永不过期。

    Cookie存储的数据量受限制,大多数的浏览器为4K因此不要存放大数据。

    由于并非所有的浏览器都支持Cookie,数据将以明文的形式保存在客户端。

    一、创建Cookie:发送到客户端浏览器

    Domain和Path相同的所有Cookie在客户端存在于一个文件中。

    //通用设置
    Response.Cookies["userName"].Value = "Park";
    Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);//不设Expires默认关闭浏览器就过期
    Response.Cookies["userName"].Domain = "park.aa.com";//Domain默认为域名部分,以表示aa.com下的所有子域名。
    Response.Cookies["userName"].Path = "App1";//Path默认为根目录"/",表示根目录下的所有页面和子目录
    
    //单值Cookie
    HttpCookie Cookie = new HttpCookie("userName");
    cookie.Value = "Park";
    cookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(cookie);
    
    //多值Cookie
    HttpCookie cookies = new HttpCookie("userName");
    cookies["name"] = "Park";
    cookies["sex"] = "1";
    cookies.Expires = DateTime.Now.AddMinutes(20);
    Response.Cookies.Add(cookies);
    //Response.SetCookies(cookies)
    //Response.AppendCookis(cookies);

    二、读取Cookie:

    Domain、Path和Expires是无法读取的

    if (Request.Cookies["userName"] != null)
    {
        //读取多值Cookie
        Response.Write(Request.Cookies["userName"].Value) //可以Server.HtmlEncode()编码
       //读取多值Cookie
        Response.Write("Cookie中键值为userid的值:" + Request.Cookies["userName"]["sex"]);
    }

    三、修改Cookie

    不能直接修改一个Cookie,是创建一个同名的Cookie,并把该Cookie发送到浏览器覆盖客户机上的旧Cookie。

    HttpCookie cok = Request.Cookies["userName"];//获取客户端的Cookie对象
    if (cok != null)
    {
        cok.Values["userid"] = "alter-value";//修改Cookie        
        cok.Values.Set("newid", "newValue");//往Cookie里加入新的内容
        Response.AppendCookie(cok);
    
        //或者
        Response.Cookies["userName"].Value = "aa";
    }
     
    Response.Cookies["Porschev"].Expires = DateTime.Now.AddMinutes(-1); 

    四、删除Cookie:

    无法直接删除一个Cookie,可通过修改它的Expires为过去的某个时间,浏览器会删除已经过期的Cookie。

    Response.Cookies["userName"].Expires = DateTime.Now.AddDays(-1);
    
    //或者
    HttpCookie cok = Request.Cookies["userName"];
    if (cok != null)
    {
        if (!CheckBox1.Checked)
        {
            cok.Values.Remove("userid");//移除键值为userid的值
        }
        else
        {
            TimeSpan ts = new TimeSpan(0, 0, 0, 0);
            cok.Expires = DateTime.Now.Add(ts);//删除整个Cookie,只要把过期时间设置为现在
        }
        Response.AppendCookie(cok);
    }

    五、Asp.Net文件上传控件:FileUpload

    ASP.NET 包含两个控件可以使用户向网页服务器上传文件。一旦服务器接受了上传的文件数据,那么应用程序就可以进行保存,进行检查或者忽略它。

    • HtmlInputFile - HTML 服务器控件
    • FileUpload - ASP.NET 网页控件

    两种控件都允许文件上传,但是 FileUpload 控件自动设置编码格式,然而 HtmlInputFile 控件并不会这样。

    1、使用HtmlInputFile文件上传

    前台

    <form  enctype="multipart/form- data">
      <input type="file" name="myfile"/>
    </form>

    后台:

    //上传文件保存路径  
    string savePath = Server.MapPath("UploadFiles") + "\";
    
    //提供对客户端上载文件的访问
    HttpFileCollection uploadFiles = System.Web.HttpContext.Current.Request.Files;
    
    for (int i = 0; i < uploadFiles.Count; i++)
    {
        System.Web.HttpPostedFile postedFile = uploadFiles[i];
        string fileName = postedFile.FileName;//完整的路径
        fileName = System.IO.Path.GetFileName(postedFile.FileName); //获取到名称
        string fileExtension = System.IO.Path.GetExtension(fileName);//文件的扩展名称
        string type = fileName.Substring(fileName.LastIndexOf(".") + 1);    //类型  
        if (uploadFiles[i].ContentLength > 0)
            uploadFiles[i].SaveAs(savePath + fileName);
    }

    2、使用FileUpload 上传:

    FileUpload 类是从 WebControl 类中得出的,并且它继承了它的所有元素,FileUpload 类具有以下这些只读属性:

    • FileBytes:返回一组将要上传文件的字节码
    • FileContent:返回将要被上传的的文件的流对象
    • FileName:返回将以上传的文件名称
    • HasFile:判断控件是否有文件需要上传
    • PostedFile:返回一个关于已上传文件的参考。

    发布的文件以 HttpPostedFile 形式的对象进行封装,这个对象可以通过 FileUpload 类的 PostedFile 属性被存取。HttpPostedFile 类具有以下常用的属性:

    • ContentLength:返回已上传的文件的字节大小
    • ContentType:返回已上传的文件的 MIME 类型
    • FileName:返回文件全名
    • InputStream:返回将要被上传的的文件的流对象

    前台:

    <form id="form1" runat="server">
          <div>
             <asp:FileUpload ID="FileUpload1" runat="server" />
             <br /><br />
             <asp:Button ID="btnsave" runat="server" onclick="btnsave_Click"  Text="Save" style="85px" />
             <br /><br />
             <asp:Label ID="lblmessage" runat="server" />
          </div>
    
       </form>

    后台:

    protected void btnsave_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
    
        if (FileUpload1.HasFile)
        {
            try
            {
                sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);
    
                //saving the file
                FileUpload1.SaveAs("<c:\SaveDirectory>" + FileUpload1.FileName);
    
                //Showing the file information
                sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName);
                sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType);
                sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength);
                sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName);
    
            }
            catch (Exception ex)
            {
                sb.Append("<br/> Error <br/>");
                sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
            }
        }
        else
        {
            lblmessage.Text = sb.ToString();
        }
    }

    3、配置可上传大文件

    Web.config配置可上传大文件,asp.net默认情况之下只能上传4MB,另外一点就是,maxRequestLength单位是MB。

    <system.web>      
            <httpRuntime maxRequestLength="102400" useFullyQualifiedRedirectUrl="true" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true"/>
    </system.web>
  • 相关阅读:
    [Swift]LeetCode156.二叉树的上下颠倒 $ Binary Tree Upside Down
    [Swift]LeetCode155. 最小栈 | Min Stack
    [Swift]LeetCode154. 寻找旋转排序数组中的最小值 II | Find Minimum in Rotated Sorted Array II
    CXF生成client注意事项
    使用oracle10g官方文档找到监听文件(listener.ora)的模板
    在Vi里面实现字符串的批量替换
    C语言之基本算法12—谁是冠军
    虚拟机 minimal 安装增强包
    ZOJ
    leetcode Reverse Nodes in k-Group
  • 原文地址:https://www.cnblogs.com/springsnow/p/9433972.html
Copyright © 2020-2023  润新知