Azure Загрузка файлового хранилища с WriteRange, а MD5 - KO - PullRequest
0 голосов
/ 06 августа 2020

Я пытаюсь загрузить файл в хранилище azure с помощью библиотеки C# REST API. Я хочу иметь возможность загрузить файл с процентом загрузки, поэтому я просмотрел документацию и попытался получить это с помощью метода WriteRange.

Он работает, но я не могу сохранить MD5 файла ( и получить его позже).

Это мой случай повторения:

static void Main(string[] args)
{
    var storageAccount = CloudStorageAccount.Parse(connectionString);
    var fileClient = storageAccount.CreateCloudFileClient();
    var share = fileClient.GetShareReference(shareReference);
    var rootDir = share.GetRootDirectoryReference();

    var firstFileCloudName = "test/file1.txt";
    var firstFilePath = "c:\\test\\file1.txt";
    var secondFileCloudName = "test/file2.txt";
    var secondFilePath = "c:\\test\\file2.txt";

    // upload first file
    var firstFile = rootDir.GetFileReference(firstFileCloudName);
    firstFile.UploadFromFile(firstFilePath, options: new FileRequestOptions { StoreFileContentMD5 = true });

    // check md5 of first file
    var checkFirstFile = rootDir.GetFileReference(firstFileCloudName);
    if (checkFirstFile.Exists() && checkFirstFile.Properties.ContentMD5 == Convert.ToBase64String(MD5.Create().ComputeHash(File.ReadAllBytes(firstFilePath))))
    {
        Console.WriteLine("First file OK"); // OK
    }

    // upload second file with chunks
    var secondFile = rootDir.GetFileReference(secondFileCloudName);
    Upload(secondFile, secondFilePath);

    // check md5 of second file
    var checksecondFile = rootDir.GetFileReference(secondFileCloudName);
    if (checksecondFile.Exists() && checksecondFile.Properties.ContentMD5 == Convert.ToBase64String(MD5.Create().ComputeHash(File.ReadAllBytes(secondFilePath))))
    {
        Console.WriteLine("Second file OK"); // KO !!!
    }

    // but the file is correctly uploaded because downloaded md5 is OK
    var downloadedFile = rootDir.GetFileReference(secondFileCloudName);
    var memoryStream = new MemoryStream();
    downloadedFile.DownloadToStream(memoryStream);
    if (Convert.ToBase64String(MD5.Create().ComputeHash(memoryStream.ToArray())) == Convert.ToBase64String(MD5.Create().ComputeHash(File.ReadAllBytes(secondFilePath))))
    {
        Console.WriteLine("Second file downloaded OK"); // KO !!!
    }
}

private static void Upload(CloudFile currentFile, string file)
{
    var options = new FileRequestOptions { StoreFileContentMD5 = true };

    long bytesToUpload = new FileInfo(file).Length;
    long fileSize = bytesToUpload;
    currentFile.Create(fileSize);
    var blockSize = 256 * 1024;
    currentFile.StreamWriteSizeInBytes = blockSize;
            
    int index = 1;
    long startPosition = 0;
    long bytesUploaded = 0;
    var allBytes = File.ReadAllBytes(file);
    var ms = new MemoryStream(allBytes);

    do
    {
        var bytesToRead = Math.Min(blockSize, bytesToUpload);
        var blobContents = new byte[bytesToRead];
        ms.Position = startPosition;
        ms.Read(blobContents, 0, (int)bytesToRead);

        var md5 = Convert.ToBase64String(MD5.Create().ComputeHash(new MemoryStream(blobContents)));
        currentFile.WriteRange(new MemoryStream(blobContents), startPosition, md5, options: options);

        bytesUploaded += bytesToRead;
        bytesToUpload -= bytesToRead;
        startPosition += bytesToRead;
        index++;
        double percentComplete = (double)bytesUploaded / fileSize;
        Console.WriteLine("Percent complete = " + percentComplete.ToString("P"));
    }
    while (bytesToUpload > 0);

    currentFile.SetProperties(options: options);
}

Некоторые пояснения:

Первый случай, загрузка с помощью UploadFromFile: он работает, и я могу сохранить и прочтите MD5. (На портале azure я вижу, что MD5 правильно хранится в свойствах)

Второй случай, при загрузке custum ContentMD5 имеет значение null. (Я вижу на портале azure, что MD5 не хранится в свойствах)

Но когда я загружаю второй файл и вычисляю md5, файл правильный, поэтому загрузка в порядке.

Как я могу сохранить MD5 в файле azure при второй загрузке? (или изменить способ загрузки в процентах)

1 Ответ

0 голосов
/ 06 августа 2020

Фактически, в конце загрузки я могу установить MD5 вручную; Думал только получить:

currentFile.Properties.ContentMD5 = md5;
currentFile.SetProperties();
...