Have to upload large files on Dropbox. I want to implement also and progress bar for upload. Everywhere it is mentioned that I should use UploadSessionStartAsync. What I do not know is how to overwrite existing file (when it already exists) with UploadSessionStartAsync. I could first delete file and then do a new upload and that works fine, but I can not do that as filemetadata of previous file is then lost. With UploadAsync it is easy as there is already a WriteMode.Overwrite argument! Here is my code:
/// <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);
}
}
}
}
}
}
When using upload sessions in the Dropbox API v2 .NET SDK, you can set the WriteMode
in the CommitInfo
that you pass to UploadSessionFinishAsync
.
That would look like this:
await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName, mode:WriteMode.Overwrite.Instance), memStream);