WPF客户端上传多个小文件至服务端,展示上传进度

上传期间可不断继续上传新的内容

效果:

 

 

 

 

 后台代码:

public partial class Upload : Window
{
//当前上传到第几个文件
int current = 0;
//已上传了多少byte
long uploadedByte =0;
//共有多少byte
long allByte=0;
//大约还需多少秒完成上传
int Second=1;
//文件路径集合
List<string> list = new List<string>();
public Upload()
{
InitializeComponent();
}

public void AddTask(List<string> newlist)
{
int addcount = newlist.Count;
//向路径集合中添加新的路径
for (int i = 0; i < addcount; i++)
{
list.Add(newlist[i]);
FileInfo file = new FileInfo(newlist[i]);
allByte += file.Length;
}

progress.Content = current + "/" + list.Count;
//判断当前是否正在进行上传,如果没有,则开始上传
if (current + addcount == list.Count)
{
StartUpload();
CountDown();
UploadInfo.Visibility = Visibility.Visible;
}
}
private async void StartUpload()
{
Random r = new Random();
//当前文件数量
int currentTotal = list.Count;
await Task.Run(async () => {
for (int i = current; i < currentTotal; i++)
{
var beginTime = DateTime.Now;
FileInfo file = new FileInfo(list[current]);
long len = file.Length;

Thread.Sleep(r.Next(1000,3000));
await CommonHelper.Upload_Request(CommonHelper.GetUrl() + "/Upload/Receive", list[current], file.Name);
var endTime = DateTime.Now;
var speed_second = Math.Round((len / 1024D / (((endTime - beginTime).Ticks) / 10000D)) * 1000);
uploadedByte += len;
Second = Convert.ToInt32(Math.Round((allByte - uploadedByte) / 1024 / speed_second));
await Dispatcher.BeginInvoke(new Action(() => {
//改变当前上传数和用户提示
current++;
progress.Content = current + "/" + list.Count;
speed.Content = speed_second + "k/S";
}));

}
});
//判断是否又添加了新的上传路径
if (current != list.Count)
StartUpload();
else
{
//结束上传
current = 0;
list = new List<string>();
uploadedByte = 0;
allByte = 0;
Second = 1;

UploadInfo.Visibility = Visibility.Collapsed;
}
}
private async void CountDown()
{
await Task.Run(async ()=> {

while(list.Count>0)
{
Thread.Sleep(1000);
//只有成功上传了一个文件后才开始计算秒数
if (current == 0)
continue;
await Dispatcher.BeginInvoke(new Action(() => {
//改变剩余秒数
countdown.Content = $"{Second}秒";
}));
Second -= 1;
if (Second <= 0)
Second = 1;
}
});
}

}

 

posted @ 2021-04-16 16:04  奇迹之耀  阅读(422)  评论(0编辑  收藏  举报