Search code examples
c#asp.net-core.net-core

Tusdotnet Upload and Download Files .Net Core


Tusdotnet is built for File uploads with .NET core Implementations, which are larger in size (If in case its gets stuck it will be resume from the same point).

  • ASP .NET Core Implementation for uploading File:
    app.UseTus(httpContext => new DefaultTusConfiguration
    {
        // c:\tusfiles is where to store files
        Store = new TusDiskStore(@"C:\tusfiles\"),
        // On what url should we listen for uploads?
        UrlPath = "/files",
        Events = new Events
        {
            //OnFileCompleteAsync = eventContext =>
            OnFileCompleteAsync = async eventContext =>
            {
    
                //return Task.CompletedTask;
                ITusFile file = await eventContext.GetFileAsync();          
                if (file != null)
                {
                    //Convert in to a FileStream
                    //var fileStream = await file.GetContentAsync(httpContext.RequestAborted);
                }
            }
        }
    }

https://github.com/tusdotnet/tusdotnet

  • After upload in folder system: enter image description here

I need to ask that:

  • For download the file we need to write a custom code but how it will be possible to identify the file extension at that level.
  • And what technique we need to use for download File, as Tusdotnet said we are not responsible for downloading the file.

Solution

  • After investigating with Tusdotnet I found only two options:

    First Approach

    Renaming of file when the file is successfully uploaded in the folder system. (As tusdotnet not maintain file extension when its upload successfully. enter image description here

    Second Approach

    Parallelly when tusdotnet upload your file successfully, upload same file with extension as well by using below code:

    OnFileCompleteAsync = async eventContext =>
    {    
        ITusFile file = await eventContext.GetFileAsync();
        if (file != null)
        {
            var fileStream = await file.GetContentAsync(httpContext.RequestAborted);
            var metadata = await file.GetMetadataAsync(httpContext.RequestAborted);
        
            httpContext.Response.ContentType = metadata.ContainsKey("contentType")
                                             ? metadata["contentType"].GetString(Encoding.UTF8)
                                             : "application/octet-stream";
        
            //Providing New File name with extension
            string name = "NewFileName.jpg";
            string networkPath = @"C:\tusfiles\";
        
            using (var fileStream2 = new FileStream(networkPath + "\\" + name, FileMode.Create, FileAccess.Write))
            {
                await fileStream.CopyToAsync(fileStream2);
            }
        }
    }
    

    Reference:

    enter image description here