示例#1
0
        /// <remarks>
        /// http://blog.geuer-pollmann.de/blog/2014/07/21/uploading-blobs-to-azure-the-robust-way/
        /// http://wely-lau.net/2012/02/26/uploading-big-files-in-windows-azure-blob-storage-with-putlistblock/
        /// </remarks>
        private static async Task UploadStreamAsync(CloudBlockBlob blob, Stream st, Action <long> uploadProgress = null)
        {
            bool small    = false;
            long uploaded = 0;

            try
            {
                small = st.Length <= UploadChunkSize;
            }
            catch (Exception) { }
            if (small)
            {
                uploaded = st.Length;
                await blob.UploadFromStreamAsync(st);
            }
            else
            {
                var blocklist = new List <string>();
                var buf       = new byte[UploadChunkSize];
                for (;;)
                {
                    var read = await st.ReadAsync(buf, 0, buf.Length);

                    if (read <= 0)
                    {
                        break;
                    }
                    var blockId = Base64.ToBase64String(Salt.CreateRandomBuf(32));
                    using (var mst = new MemoryStream(buf, 0, read, false))
                    {
                        await blob.PutBlockAsync(blockId, mst, null);
                    }
                    uploaded += read;
                    uploadProgress?.Invoke(uploaded);
                    blocklist.Add(blockId);
                }
                await blob.PutBlockListAsync(blocklist);
            }
            uploadProgress?.Invoke(uploaded);
        }