【问题标题】:Use compressed gzip file with UploadBlobAsync method使用带有 UploadBlobAsync 方法的压缩 gzip 文件
【发布时间】:2021-06-15 09:57:55
【问题描述】:

我想压缩一个 json 字符串并将其保存为 gzip 文件。我在下面有以下代码,但仅将其保存为 .json 文件。使用压缩文件更小。如果我压缩 json 字符串并将文件名更改为 .gz,我无法使用 7zip 打开它。

        string containerEndpoint = string.Format("https://xxx.blob.core.windows.net/datafolder");
        BlobContainerClient containerClient = new BlobContainerClient(new Uri(containerEndpoint), null);

        byte[] byteArray = Encoding.ASCII.GetBytes(jsonString);
        MemoryStream stream = new MemoryStream(byteArray);

        string fileName = "test.gz";
        string blobPath = string.Format("folder/{0}", fileName);

        await containerClient.UploadBlobAsync(blobPath, stream);

【问题讨论】:

  • 您可以使用 GZipStream 和 MemoryStream 在 UploadBlobAsync 之前生成 outStream
  • 上传前你在哪里压缩内容?只需将文件扩展名更改为gz 不会压缩内容。
  • 无关:请注意,使用此处的 ASCII 编码会失去 unicode 兼容性。 (可能不相关,只是说)您还应该优雅地处理 MemoryStream(“使用”)。

标签: c# azure azure-blob-storage


【解决方案1】:

我添加了您的建议并且它有效。我的代码现在如下:

        byte[] buffer = Encoding.UTF8.GetBytes(json);

        using (var stream = new MemoryStream())
        {

            using (var gZipStream = new GZipStream(stream, CompressionMode.Compress, true))
            {
                gZipStream.Write(buffer, 0, buffer.Length);
            }

            var compressedData = new byte[stream.Length];
            stream.Read(compressedData, 0, compressedData.Length);

            var gZipBuffer = new byte[compressedData.Length + 4];
            Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
            stream.Position = 0;
            string blobPath = string.Format("folder/{0}", fileName);
            await containerClient.UploadBlobAsync(blobPath, stream);

        }

【讨论】:

  • 如果您希望浏览器自动解压gz文件,请确保将blob的Content-Encoding属性设置为gzip。 HTH。
猜你喜欢
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多