Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Direct Upload to Tencent Cloud OSS: A Practical Example

Tools May 13 2

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);
            }
        }
    }
}

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.