Vla*_*usB 2 c# dropbox dropbox-sdk
必须在 Dropbox 上上传大文件。我也想实现上传进度条。到处都提到我应该使用 UploadSessionStartAsync。我不知道如何使用 UploadSessionStartAsync 覆盖现有文件(当它已经存在时)。我可以先删除文件,然后进行新的上传,效果很好,但我不能这样做,因为之前文件的文件元数据丢失了。使用 UploadAsync 很容易,因为已经有一个 WriteMode.Overwrite 参数!这是我的代码:
/// <summary>
/// Uploads a big file in chunk. The is very helpful for uploading large file in slow network condition
/// and also enable capability to track upload progerss.
/// </summary>
/// <param name="client">The Dropbox client.</param>
/// <param name="folder">The folder to upload the file.</param>
/// <param name="fileName">The name of the file.</param>
/// <returns></returns>
private async Task ChunkUpload(DropboxClient client, string folder, string fileName)
{
Console.WriteLine("Chunk upload file...");
// Chunk size is 128KB.
const int chunkSize = 128 * 1024;
// Create a random file of 1MB in size.
var fileContent = new byte[1024 * 1024];
new Random().NextBytes(fileContent);
using (var stream = new MemoryStream(fileContent))
{
int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize);
byte[] buffer = new byte[chunkSize];
string sessionId = null;
for (var idx = 0; idx < numChunks; idx++)
{
Console.WriteLine("Start uploading chunk {0}", idx);
var byteRead = stream.Read(buffer, 0, chunkSize);
using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead))
{
if (idx == 0)
{
var result = await client.Files.UploadSessionStartAsync( body: memStream);
sessionId = result.SessionId;
}
else
{
UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx));
if (idx == numChunks - 1)
{
await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName), memStream);
}
else
{
await client.Files.UploadSessionAppendV2Async(cursor, body: memStream);
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当使用上传会话Dropbox的API V2 .NET SDK,可以设置WriteMode在CommitInfo你传递给UploadSessionFinishAsync。
那看起来像这样:
await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName, mode:WriteMode.Overwrite.Instance), memStream);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
719 次 |
| 最近记录: |