Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gzip and upload to Azure blob

Tags:

gzip

c#-4.0

azure

I am trying to gzip and upload a static js file to an Azure blob, but I end up with a 0 byte 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);
}
}
like image 774
user2628438 Avatar asked Jul 28 '13 22:07

user2628438


1 Answers

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.

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. I've been burned by it several times.

like image 69
MikeWo Avatar answered Sep 21 '22 02:09

MikeWo