user2628438
user2628438

Reputation: 169

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. 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);
}
}

Upvotes: 5

Views: 6155

Answers (1)

MikeWo
MikeWo

Reputation: 10975

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.

Upvotes: 8

Related Questions