将文件以块的形式上传到Azure

时间:2014-04-24 08:40:04

标签: c# asp.net azure blob azure-storage-blobs

当我尝试将多个文件(以块为单位)上传到Windows Azure时,只会保存最新的文件。

我跟着this教程(工作正常)和一个文件。当我选择多个文件并开始上传它们时,当我将阻止列表放入blob文件时,它总是在Commit方法中崩溃。

错误:

  

Microsoft.WindowsAzure.Storage.StorageException:远程服务器   返回错误:(400)错误请求。 ---> System.Net.WebException:   远程服务器返回错误:(400)错误请求。在   System.Net.HttpWebRequest.GetResponse()at   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync [T](RESTCommand 1 cmd, IRetryPolicy policy, OperationContext operationContext) --- End of inner exception stack trace --- at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand 1   cmd,IRetryPolicy策略,OperationContext operationContext)at   Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.PutBlockList(IEnumerable`1   blockList,AccessCondition accessCondition,BlobRequestOptions   options,OperationContext operationContext)at   VERPData.Controllers.ArticlesController.Commit()in   c:\ Users \ PJDW \ Documents \ School \ 3NMCT \ Stage en   Bachelorproef \级\ lerp_git \线性插值\线性插值\ \控制器ArticlesController.cs:行   1015请求信息   RequestID:6fc7cef3-99bb-4f0c-8271-0cd72e41f3be RequestDate:4月24日星期四   2014 08:16:30 GMT StatusMessage:指定的阻止列表无效。   错误码:InvalidBlockList

当我搜索“指定的阻止列表无效”时,我发现了一些像here这样的技巧来设置所有阻止ID的长度相同但它不起作用。

例如: 我改变了这段代码:

var id = Convert.ToBase64String(BitConverter.GetBytes(index));

var id = Convert.ToBase64String(Encoding.UTF8.GetBytes(index.ToString("d8")));

更新:完整代码 的 Azure.js

$(function () {
    $("#upload").click(function () {
        //get GUID
        var guid = $("#getID").val();

        // start to upload each files in chunks
        var test = $("#dropzone-files");
        var files = $("#dropzone-files")[0].dropzone.files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var fileSize = file.size;
            var fileName = guid + "_" + file.name;

            // calculate the start and end byte index for each blocks(chunks)
            // with the index, file name and index list for future using
            var blockSizeInKB = 2048;
            var blockSize = blockSizeInKB * 1024;
            var blocks = [];
            var offset = 0;
            var index = 0;
            var list = "";
            while (offset < fileSize) {
                var start = offset;
                var end = Math.min(offset + blockSize, fileSize);

                blocks.push({
                    name: fileName,
                    index: index,
                    start: start,
                    end: end
                });
                list += index + ",";

                offset = end;
                index++;
            }

            // define the function array and push all chunk upload operation into this array
            var putBlocks = [];
            blocks.forEach(function (block) {
                putBlocks.push(function (callback) {
                    // load blob based on the start and end index for each chunks
                    var blob = file.slice(block.start, block.end);
                    // put the file name, index and blob into a temporary form
                    var fd = new FormData();
                   // fd.append("name", $('#getID').val() + "_" + block.name);
                    fd.append("name", block.name);
                    fd.append("index",block.index);
                    fd.append("file", blob);

                    // post the form to backend service (asp.net mvc controller action)
                    $.ajax({
                        url: "/Articles/UploadInFormData",
                        data: fd,
                        processData: false,
                        contentType: false,
                        type: "POST",
                        success: function (result) {
                            if (!result.success) {
                                alert(result.error);
                            }
                            callback(null, block.index);
                        }
                    });
                });
            });

            // invoke the functions one by one
            // then invoke the commit ajax call to put blocks into blob in azure storage
            async.parallelLimit(putBlocks,4, function (error, result) {
                var data = {
                    name: fileName,
                    list: list
                };
                $.post("/Articles/Commit", data, function (result) {
                    if (!result.success) {
                        alert(result.error);
                    }
                    else {
                        alert("done!");
                    }
                });
            });
        }
    });
});

CONTROLLER

    [HttpPost]
    public JsonResult UploadInFormData()
    {
        var error = string.Empty;
        try
        {
            var name = Request.Form["name"];
            var index = int.Parse(Request.Form["index"]);
            var file = Request.Files[0];
            var id = Convert.ToBase64String(Encoding.UTF8.GetBytes(index.ToString("D8")));

            AzureHelper _azureHelper = new AzureHelper();
            _azureHelper.UploadInBlocksToAzure("verparticleattachments", name, id, file);
        }
        catch (Exception e)
        {
            error = e.ToString();
            UserCredentials user = (UserCredentials)(Session["UserCredentials"]);
            ErrorLogger.WriteLog(e.StackTrace, user.UserContactID);
        }
        return new JsonResult()
        {
            Data = new
            {
                success = string.IsNullOrWhiteSpace(error),
                error = error
            }
        };
    }



[HttpPost]
public JsonResult Commit()
{
    var error = string.Empty;
    try
    {
        var name = Request.Form["name"];
        var list = Request.Form["list"];
        var ids = list
            .Split(',')
            .Where(id => !string.IsNullOrWhiteSpace(id))
            .Select(id => Convert.ToBase64String(Encoding.UTF8.GetBytes(int.Parse(id).ToString("D8"))))
            .ToArray();

        AzureHelper _azureHelper = new AzureHelper();
        var container = _azureHelper.GetCloudBlobContainer("verparticleattachments");
        var blob = container.GetBlockBlobReference(name);
        blob.PutBlockList(ids);
    }
    catch (Exception e)
    {
        error = e.ToString();
        UserCredentials user = (UserCredentials)(Session["UserCredentials"]);
        ErrorLogger.WriteLog(e.StackTrace.ToString(), user.UserContactID);
    }

    return new JsonResult()
    {
        Data = new
        {
            success = string.IsNullOrWhiteSpace(error),
            error = error
        }
    };
}

AZURE HELPER

public void UploadInBlocksToAzure(string containername,string name, string id, HttpPostedFileBase file)
{
    try
    {
    var container = GetCloudBlobContainer(containername);
    var blob = container.GetBlockBlobReference(name);
    blob.PutBlock(id, file.InputStream, null);
    }catch(Exception ex)
    {
        ErrorLogger.WriteLog(ex.StackTrace, null);
    }

}

0 个答案:

没有答案