Docs_SaveToServer.razor

1. OpenReadOnlyStream

In demo MyUploaderState.cs , use OpenReadOnlyStream to get a stream which allow developer read data from browser

The demo code do these jobs:

  • Open stream from browser
  • Save the upload start time
  • Get a server temp file path
  • Open the stream for temp file
  • loop to read data from browser
  • Check whether the file be cancelled by user or not
  • Save the state of reading file so can calculate percent/speed later
  • Send the StateHasChanged event every 0.2 second
  • Delete the temp file if cancelled or error throws

                using Stream s = f.OpenReadOnlyStream();

                DateTime updatetime = DateTime.Now;

                f.UserTotalReadSize = 0;

                f.UserReadStartTime = DateTime.Now;

                f.UserTempFilePath = Program.GetTempFileName(f.Uploader.UniqueId, f.FileId);

                try

                {

                    using Stream fs = File.OpenWrite(f.UserTempFilePath);

                    while (true)

                    {

                        sw.Restart();

                        int rc = await s.ReadAsync(buffer, 0, buffer.Length);

                        if (rc == 0)

                            break;

                        if (f.UserCancelled)

                            break;

                        await fs.WriteAsync(buffer, 0, rc);

                        TimeSpan latency = sw.Elapsed;

                        if (f.UserMaxReadLatency < latency) f.UserMaxReadLatency = latency;

                        f.UserTotalReadSize += rc;

                        f.UserTotalReadTimeSpan += latency;

                        f.UserTotalReadTimes++;

                        if (DateTime.Now - updatetime > TimeSpan.FromSeconds(0.2))

                        {

                            CurrentActionMsg = "read " + f.FileName + " " + f.UserTotalReadSize;

                            updatetime = DateTime.Now;

                            InvokeStateHasChanged();

                        }

                    }

                }

                catch (Exception fx)

                {

                    f.UserError = fx.Message;

                    try { File.Delete(f.UserTempFilePath); } catch { }

                    throw;

                }

                if (f.UserCancelled)

                {

                    try { File.Delete(f.UserTempFilePath); } catch { }

                }

}

The file will be saved to UserTempFilePath

Check the Docs_PreviewImage.razor to know how to use it.

An error has occurred. This application may no longer respond until reloaded. Reload 🗙