简体   繁体   English

Gzip并上传到Azure blob

[英]Gzip and upload to Azure blob

I am trying to gzip and upload a static js file to an Azure blob, but I end up with a 0 byte blob. 我正在尝试gzip并将静态js文件上传到Azure blob,但我最终得到一个0字节的blob。 Can someone tell me what I'm doing wrong? 有人能告诉我我做错了什么吗?

var filePath = "C:\test.js";

using (var compressed = new MemoryStream()) {
using (var gzip = new GZipStream(compressed, CompressionMode.Compress)) {
    var bytes = File.ReadAllBytes(filePath);
    gzip.Write(bytes, 0, bytes.Length);

    var account = CloudStorageAccount.Parse("...");
    var blobClient = new CloudBlobClient(account.BlobEndpoint, account.Credentials);
    var blobContainer = blobClient.GetContainerReference("temp");
    var blob = blobContainer.GetBlockBlobReference(Path.GetFileName(filePath));
    blob.Properties.ContentEncoding = "gzip";
    blob.Properties.ContentType = "text/javascript";
    blob.Properties.CacheControl = "public, max-age=3600";

    blob.UploadFromStream(compressed);
}
}

You need to reset the stream position to zero on the compressed stream. 您需要在压缩流上将流位置重置为零。 You've written data into the stream, but when you go to upload from the stream on the last line the position of the stream is at the end of the data you have written, so the blob.UploadFromStream starts from the current position in the stream, which has nothing after it. 您已将数据写入流中,但是当您从最后一行的流上传时,流的位置位于您编写的数据的末尾,因此blob.UploadFromStream从当前位置开始流,后面没有任何东西。

add the following before you perform the upload: 在执行上载之前添加以下内容:

compressed.Position = 0;

That should upload the full contents of the stream. 那应该上传流的全部内容。

This isn't necessarily an Azure thing, most code that works with streams operate of the current position for the stream. 这不一定是Azure的东西,大多数使用流的代码都会对流的当前位置进行操作。 I've been burned by it several times. 我被它烧了几次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM