【问题标题】:Why do I lose data when I minify JS and CSS with GZip?为什么我在使用 GZip 压缩 JS 和 CSS 时会丢失数据?
【发布时间】:2011-11-18 03:40:53
【问题描述】:

我遇到了一个关于 GZip 的奇怪问题,希望您能帮助我。

using (MemoryStream memoryStream = new MemoryStream(10240))
{
   //isCompressed will be true if the browser accepts gzip
   using (Stream writer = isCompressed ?
                    (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) :
                    memoryStream)
   {
      StringBuilder sb = new StringBuilder();

      //filenames is collection of multi js files need to be minify
      foreach (string fileName in fileNames)
      {
         sb.Append(File.ReadAllText(context.Server.MapPath(fileName)));
      }

      //minifier is an instance of Microsoft.Ajax.Utilities.Minifier
      string minifiedString = minifier.MinifyJavaScript(sb.ToString());

      byte[] bts = Encoding.UTF8.GetBytes(minifiedString);
      writer.Write(bts, 0, bts.Length);
   }
}

bts的长度其实是6000多,但是writer.Write(bts, 0, bts.length)执行的时候,writer只能写2334个字符,我查了里面的资料,说,操作不支持,我很困惑,我不知道为什么?

【问题讨论】:

    标签: c# asp.net gzip minify


    【解决方案1】:

    如果我理解这种情况,Vinay 是正确的,正在压缩 6k。但是,为什么要使用自定义代码来压缩您的内容呢?为什么不在 IIS 中打开静态和动态压缩,让 IIS 完成工作?此外,使用像 http://RequestReduce.com 这样的库,它会自动组合和缩小您的 css 和 js,无需代码,也可能无需配置,也无需精灵图像。

    【讨论】:

    • 在 IIS 中打开静态和动态压缩并不总是一种选择。例如,如果他使用共享主机,一些托管公司会在共享计划中禁用它。对于这个减少,我仍然使用我的自定义库进行压缩/缩小。
    • 好点。您知道哪些流行的托管服务提供商不允许 IIS 压缩?
    • 如果托管服务提供商不允许您打开 gzip,我认为更改托管服务提供商...
    【解决方案2】:

    但是为什么你会感到困惑?这里的想法不是压缩脚本 - 所以 gzip 流将占用几个字节并将压缩它们 - 因此生成的数据将比输入数据小。所以你的 6000 字节被压缩成 2334 字节。

    【讨论】:

      猜你喜欢
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      相关资源
      最近更新 更多