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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With