Direct Upload to Tencent Cloud OSS: A Practical Example
namespace CloudStorageUpload { public class FileUploadService { private static FileUploadService _instance; private static ConcurrentQueue _uploadQueue = new ConcurrentQueue(); private static int _activeTasks; private static readonly int MaxConcurrentTasks = 2; private Thread _workerThread; private DateTime _startTime;
public enum UploadStatus
{
[Display(Name = "Pending")]
Pending = 0,
[Display(Name = "In Progress")]
InProgress = 1,
[Display(Name = "Completed")]
Completed = 2,
[Display(Name = "Failed")]
Failed = 3,
}
public static FileUploadService GetInstance()
{
return _instance ?? (_instance = new FileUploadService());
}
private FileUploadService()
{
}
public void Initialize()
{
_workerThread = new Thread(ProcessQueue);
_startTime = DateTime.Now;
}
private void ProcessQueue()
{
while (true)
{
if (_uploadQueue.Count > 0 && _activeTasks < MaxConcurrentTasks)
{
if (_uploadQueue.TryDequeue(out string filePath))
{
ExecuteUpload(filePath);
}
}
else
{
Thread.Sleep(500);
}
}
}
private async void ExecuteUpload(string filePath)
{
_activeTasks++;
try
{
await Task.Run(() => UploadFile(filePath));
}
catch (Exception ex)
{
Debug.WriteLine($"Upload error: {ex.Message}");
}
finally
{
_activeTasks--;
}
}
public void EnqueueFile(string filePath)
{
if (!string.IsNullOrEmpty(filePath))
{
_uploadQueue.Enqueue(filePath);
}
}
private void UploadFile(string sourcePath)
{
if (string.IsNullOrEmpty(sourcePath)) return;
string fileName = Path.GetFileName(sourcePath);
string remotePath = $"GctAnalyse/AnswerSheet/4467690286423871488/4467701265748594688/3/4/{fileName}";
string resultUrl = CosossService.CreateOssService().SyncUploadFile(remotePath, sourcePath);
Console.WriteLine($"Upload successful: {resultUrl}");
}
}
}
</div><div>The following console application demonstrates how to invoke the upload service. It scans a specified directory for image files and adds them to the upload queue.</div><div>```
namespace CloudStorageUpload
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting file upload process...");
RunUploadDemo();
Console.ReadKey();
}
private static void RunUploadDemo()
{
FileUploadService uploadService = FileUploadService.GetInstance();
uploadService.Initialize();
uploadService._workerThread.Start();
string directoryPath = @"D:\Pics\original";
if (!Directory.Exists(directoryPath))
{
Console.WriteLine("Directory not found!");
return;
}
string[] imageFiles = Directory.GetFiles(directoryPath, "*.jpg", SearchOption.AllDirectories);
Console.WriteLine($"Found {imageFiles.Length} files to upload");
foreach (string filePath in imageFiles)
{
uploadService.EnqueueFile(filePath);
}
}
}
}