Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

c# - Uploading Large Files from Form Upload and Progress asp.net core 5

I am uploading files which could be 2 gb in size does .net core 5 support file sizes of that size. I am using mega and I am also wanting to get back a progress value of percentage, now I no what most say this figure is abituary but I would like to give some idea to my user of when the upload would be complete.

I am using this package to using in code behind https://github.com/gpailler/MegaApiClient but I didn't see any examples of how to use a progress feed back to the end user?.

[HttpPost]
[ValidateAntiForgeryToken]        
public async Task<IActionResult> UploadFiles([FromForm]FileManagerViewModel fileManager)
{
    var uploads = Path.Combine(hostingEnvironment.WebRootPath, "Uploads");
    string uploadsUserId = uploads + @"" + UserId.ToString() + @"";

    if (!Directory.Exists(uploadsUserId))
        Directory.CreateDirectory(uploadsUserId);
         

    foreach (IFormFile formFile in fileManager.File)
    {
        string fullFile = uploads + @"" + UserId.ToString() + @"" + formFile.FileName;
        using (var stream = new FileStream(fullFile, FileMode.Create))
        {
            await formFile.CopyToAsync(stream);
        }

        if (ModelState.IsValid)
        {

            var section = ConfigurationManager.GetSection("FileTransferConfig") as NameValueCollection;
            var userName = section["UserName"];
            var password = section["Password"];
            FileClient client = new FileClient();
            FileInfo info = new FileInfo(formFile.FileName);
            var remoteIpAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress;
            await client.UploadFileAsync(_context, userName, password, fullFile, info.Extension.ToLower(), UserId.ToString(), remoteIpAddress.ToString());
        }

    }
    return View("~/Views/FileManager/Index.cshtml", _context.FileManager.Where(w => w.UserId == UserId).ToList());
}

My UploadFileAysnc as you see I do get a ProgressChanged event back but how would one show that on the ui some how gracefully to the end user. I would prefare a popup or some form of visual indication.

public async Task<double> UploadFileAsync(MSFSAddonDBContext context, string UserName,string Password, string fileName,string extension,string userId,string ipAddress)        {
    double progressValue=0.00;
    var client = new MegaApiClient();
    client.Login(UserName, Password);
        
    IEnumerable<INode> nodes = client.GetNodes();

    INode root = nodes.Single(x => x.Type == NodeType.Root);
    INode myFolder = nodes.SingleOrDefault(x => x.ParentId == root.Id && x.Type == NodeType.Directory && x.Name == userId) ?? client.CreateFolder(userId, root);
    var progress = new Progress<double>();
    progress.ProgressChanged += (s, progressValue) =>
    {
        //Update the UI (or whatever) with the progressValue 
        progressValue = Convert.ToInt32(progressValue);
    };
    if (uploadCancellationTokenSource.IsCancellationRequested)
    {
        uploadCancellationTokenSource.Dispose();
        uploadCancellationTokenSource = new CancellationTokenSource();
    }

    INode myFile =await client.UploadFileAsync(fileName, myFolder,progress, uploadCancellationTokenSource.Token);
    Uri downloadLink = client.GetDownloadLink(myFile);
    Console.WriteLine(downloadLink);
    FileManger uploadRecord= new FileManger();
    Guid.TryParse(userId, out Guid userIdValue);
    uploadRecord.UserId = userIdValue;
    uploadRecord.isZipFile = true;
    uploadRecord.OrignalFilename = fileName;
    uploadRecord.FileExtension = Path.GetExtension(fileName);
    uploadRecord.isActive = true;
    uploadRecord.IPAddressBytes = ipAddress;
    uploadRecord.isDeleted = false;
    uploadRecord.CreatedDate = DateTime.Now;
    uploadRecord.CreatedBy = UserName;
    uploadRecord.canBeDownloadedByOtherUsers = true;
    uploadRecord.DownloadLink = downloadLink.ToString();
    var upload = context.FileManager.Add(uploadRecord);
    await context.SaveChangesAsync();
    client.Logout();

    return progressValue;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...