代码之家  ›  专栏  ›  技术社区  ›  davidsleeps

确定html字符串的内容长度

  •  1
  • davidsleeps  · 技术社区  · 15 年前

    Dim html as String = "<table><tr><td>example<td></tr></table>"
    
    context.Response.Clear()
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" & "exceldata-" & Now.ToString("yyyyMMddHHmmss") & ".xls")
    'context.Response.AddHeader("Content-Length", ????)
    context.Response.ContentType = "application/octet-stream"
    context.Response.Write(response)
    context.Response.End()
    

    有没有一种根据html字符串的大小设置内容长度的简单方法?或者我应该把它留空…最好有理想的内容长度。。。

    我将使用asp.net中的generichendler返回此文件

    3 回复  |  直到 15 年前
        1
  •  5
  •   John Sheehan    15 年前

    替换为您选择的编码,可能是UTF8。对不起C#:

    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] bytes = encoding.GetBytes(html);
    int length = bytes.Length;
    

    http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.contentlength.aspx

        2
  •  1
  •   benr    15 年前

    这似乎太简单了,但它不只是等于html.Length吗?

        3
  •  1
  •   Alberto Martinez    15 年前

    我没有使用ASP.NET,但是我猜Length()方法返回的是字符串的字符长度,而不是字节长度,因此如果服务器使用UTF-8或Unicode为页面提供服务,它将不起作用。

    如另一个答案所述,让服务器为您填充它。如果考虑一下,在从ASP生成HTML页面时不必添加它,因为web服务器将根据来自ASP模块的响应生成它。

    推荐文章