添加上传按钮点击事件

dev
洁 任 2025-03-20 16:08:11 +08:00
parent 332932938c
commit 0f6cf2c2df
9 changed files with 418 additions and 33 deletions

View File

@ -17,5 +17,10 @@ namespace HeBianGu.App.Disk
{
return await ViewAsync();
}
public async Task<IActionResult> UpLoad()
{
return await ViewAsync();
}
}
}

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Hopetry.Services
{
public class AsyncRelayCommand : ICommand
{
private readonly Func<Task> _executeAsync;
private readonly Func<bool> _canExecute;
public AsyncRelayCommand(Func<Task> executeAsync, Func<bool> canExecute = null)
{
_executeAsync = executeAsync ?? throw new ArgumentNullException(nameof(executeAsync));
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
// 这个方法决定了命令是否可执行
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
// 异步执行命令
public async void Execute(object parameter)
{
if (_executeAsync != null)
{
await _executeAsync(); // 执行异步操作
}
}
// 通知命令的可执行状态发生变化
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}

View File

@ -15,7 +15,7 @@ using Polly.Retry;
namespace Hopetry.Services
{
class MinioService
public partial class MinioService
{
private readonly IMinioClient _minioClient;

63
Services/MinioService1.cs Normal file
View File

@ -0,0 +1,63 @@
using System.Collections.Concurrent;
using System.IO;
using System.Security.Cryptography;
using System.Threading.Channels;
using System.Windows.Threading;
using FileUploader.Models;
using Microsoft.Extensions.Configuration;
using Minio;
using Minio.ApiEndpoints;
using Minio.DataModel;
using Minio.DataModel.Args;
using Minio.DataModel.Notification;
using Minio.Exceptions;
namespace Hopetry.Services
{
public partial class MinioService
{
#region 多文件上传
public async void UploadFileToMinIOWithProgress(string filePath)
{
try
{
string bucketName = "test";
string objectName = System.IO.Path.GetFileName(filePath);
//判断桶是否存在
var beArgs = new BucketExistsArgs().WithBucket(bucketName);
bool found = await _minioClient.BucketExistsAsync(beArgs).ConfigureAwait(false);
if (!found)
{
var mbArgs = new MakeBucketArgs()
.WithBucket(bucketName);
await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
}
var progress = new Progress<ProgressReport>(progressReport =>
{
//Dispatcher.Invoke(() =>
//{
// progressBar.Value = progressReport.Percentage;// 更新进度条的值
//});
});
PutObjectArgs putObjectArgs = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName)
.WithFileName(filePath)
//.WithContentType("application/octet-stream")
.WithProgress(progress);
// 上传文件并提供进度反馈
await _minioClient.PutObjectAsync(putObjectArgs);
}
catch (Exception ex)
{
throw new Exception($"上传文件失败: {ex.Message}");
}
}
#endregion
}
}

View File

@ -10,7 +10,6 @@ namespace HeBianGu.App.Disk
public ExplorerControl()
{
InitializeComponent();
this.DataContext = new LoyoutViewModel();
}
}
}

View File

@ -0,0 +1,187 @@
<UserControl x:Class="HeBianGu.App.Disk.UpLoadControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:h="https://github.com/HeBianGu"
xmlns:local="clr-namespace:HeBianGu.App.Disk"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:system="clr-namespace:System;assembly=mscorlib"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
<Grid>
<DockPanel Margin="0,0,10,0">
<h:Row DockPanel.Dock="Top" Style="{DynamicResource {x:Static h:Row.Column10Key}}">
<TextBlock Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}" Text="上传总进度" />
<h:FProgressBar Grid.Column="1"
Grid.ColumnSpan="6"
Height="15"
CornerRadius="2"
Maximum="100"
Value="{Binding Progress}">
<h:FProgressBar.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard Timeline.DesiredFrameRate="{x:Static h:StoryboardSetting.DesiredFrameRate}">
<DoubleAnimation Storyboard.TargetProperty="Value"
From="0"
To="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Value}"
Duration="00:00:30" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</h:FProgressBar.Triggers>
</h:FProgressBar>
<TextBlock Grid.Column="7" Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}" Text="184 KB/s" />
<Button Grid.Column="8"
Margin="10,0"
Content="全部暂停"
Style="{DynamicResource {x:Static h:ButtonKeys.BorderBrushTransparent}}" />
<Button Grid.Column="9" Content="全部取消" Style="{DynamicResource {x:Static h:ButtonKeys.BorderBrushTransparent}}" />
</h:Row>
<!--<Grid Height="60" DockPanel.Dock="Top" TextBlock.Foreground="{DynamicResource {x:Static h:BrushKeys.Orange}}">
<Border Background="{DynamicResource {x:Static h:BrushKeys.Orange}}" Opacity="0.2" />
<TextBlock Margin="10,0"
HorizontalAlignment="Left"
FontSize="20"
Style="{DynamicResource {x:Static h:TextBlockKeys.Icon}}"
Text="&#xe771;" />
<TextBlock Margin="40,0,10,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
FontStyle="Oblique"
Text="开通超级会员,立即尊享急速下载特权!" />
<Button Height="30"
Margin="300,0,10,0"
Padding="15,0"
HorizontalAlignment="Left"
h:Cattach.CornerRadius="15"
Background="{DynamicResource {x:Static h:BrushKeys.Orange}}"
Content="免费试用"
Foreground="{DynamicResource {x:Static h:BrushKeys.ForegroundWhite}}"
Style="{DynamicResource {x:Static h:ButtonKeys.Transparent}}" />
</Grid>-->
<!--<ListBox h:Cattach.ItemHeight="Auto" Style="{DynamicResource {x:Static h:ListBoxKeys.Single}}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type h:TestViewModel}">
<Grid Height="50" Margin="10">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30" />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.RowSpan="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="30"
Style="{DynamicResource {x:Static h:TextBlockKeys.Icon}}"
Text="&#xe741;" />
<TextBlock Grid.Row="0"
Grid.Column="1"
HorizontalAlignment="Left"
Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}"
Text="{Binding Value}" />
<TextBlock Grid.Row="1"
Grid.Column="1"
HorizontalAlignment="Left"
Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}"
Text="{Binding Value1}" />
<TextBlock Grid.Row="0"
Grid.Column="2"
HorizontalAlignment="Right"
Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}"
Text="{Binding Value2}" />
<TextBlock Grid.Row="0"
Grid.Column="3"
Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}"
Text="{Binding Value3}" />
<h:FProgressBar Grid.Column="3"
Height="15"
CornerRadius="2"
Maximum="100"
Value="{Binding Int1}">
<h:FProgressBar.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard Timeline.DesiredFrameRate="{x:Static h:StoryboardSetting.DesiredFrameRate}">
<DoubleAnimation Storyboard.TargetProperty="Value"
From="0"
To="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Value}"
Duration="00:00:30" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</h:FProgressBar.Triggers>
</h:FProgressBar>
<TextBlock Grid.Row="1"
Grid.Column="3"
Margin="-3,0"
HorizontalAlignment="Left"
Style="{DynamicResource {x:Static h:TextBlockKeys.Default}}"
Text="{Binding Value3}" />
<StackPanel Grid.RowSpan="2"
Grid.Column="4"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Horizontal">
<Button h:Cattach.Icon="&#xe76e;" />
<Button h:Cattach.Icon="&#xe8a0;" h:Cattach.IconSize="13" />
<Button h:Cattach.Icon="&#xe87a;" h:Cattach.IconSize="15" />
</StackPanel>
<Border Grid.RowSpan="11"
Grid.ColumnSpan="11"
Margin="0,0,0,-8"
BorderBrush="{DynamicResource {x:Static h:BrushKeys.BorderBrushDefault}}"
BorderThickness="0,0,0,1" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<h:TestViewModel Int1="22"
Value1="701KB/21.52MB"
Value2="10:20:57"
Value3="184KB/s"
Value="FFmpeg直播推流拉流.rar" />
<h:TestViewModel Int1="45"
Value1="701KB/11.52MB"
Value2="00:20:57"
Value3="184KB/s"
Value="WPF-ControlBase-master (1).zip" />
<h:TestViewModel Int1="78"
Value1="101KB/1.53MB"
Value2="20:20:57"
Value3="284KB/s"
Value="Git-2.12.2.2-64-bit.exe" />
<h:TestViewModel Int1="11"
Value1="101KB/1.72MB"
Value2="00:40:57"
Value3="124KB/s"
Value="代码段201911271359.rar" />
<h:TestViewModel Int1="100"
Value1="2.34MB/2.34MB"
Value2=""
Value3="已完成"
Value="WPF-Chart-master.zip" />
</ListBox>-->
</DockPanel>
</Grid>
</UserControl>

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace HeBianGu.App.Disk
{
/// <summary>
/// UpLoadControl.xaml 的交互逻辑
/// </summary>
public partial class UpLoadControl : UserControl
{
public UpLoadControl()
{
InitializeComponent();
}
}
}

View File

@ -1,11 +1,16 @@
using HeBianGu.Base.WpfBase;
using HeBianGu.Service.Mvc;
using Hopetry.Services;
using Microsoft.Win32;
using Minio.DataModel.Args;
using Minio.DataModel;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Minio;
using Microsoft.Extensions.Configuration;
namespace HeBianGu.App.Disk
{
@ -86,46 +91,76 @@ namespace HeBianGu.App.Disk
}
#region 文件上传
private ICommand _uploadCommand;
public ICommand UploadCommand
private SendViewModel _sendViewModel;
private IConfiguration config;
public ICommand UploadCommand { get; }
public LoyoutViewModel(SendViewModel sendViewModel, IConfiguration _config)
{
get
_sendViewModel = sendViewModel;
config=_config;
UploadCommand = new AsyncRelayCommand(async () => await UploadFile());
}
private async Task UploadFile()
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.Multiselect = true; // 可选择多个文件
openFileDialog.Filter = "All Files (*.*)|*.*";
//openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == true)
{
return _uploadCommand ?? (_uploadCommand = new RelayCommand(UploadFile));
foreach (string filePath in openFileDialog.FileNames)
{
// 处理选择的文件
UploadFileToMinIOWithProgress(filePath);
}
}
}
private void UploadFile(object obj)
private async void UploadFileToMinIOWithProgress(string filePath)
{
//// 打开文件选择对话框
//OpenFileDialog openFileDialog = new OpenFileDialog();
//openFileDialog.Filter = "All Files (*.*)|*.*"; // 设置文件过滤器
//openFileDialog.Multiselect = false; // 单文件上传
var minioConfig = config.GetSection("Minio");
IMinioClient client = new MinioClient()
.WithEndpoint(minioConfig["Endpoint"])
.WithCredentials(minioConfig["AccessKey"], minioConfig["SecretKey"]);
try
{
string bucketName = "test";
string objectName = System.IO.Path.GetFileName(filePath);
//if (openFileDialog.ShowDialog() == true)
//{
// string filePath = openFileDialog.FileName;
// string fileName = Path.GetFileName(filePath);
//判断桶是否存在
var beArgs = new BucketExistsArgs().WithBucket(bucketName);
bool found = await client.BucketExistsAsync(beArgs).ConfigureAwait(false);
if (!found)
{
var mbArgs = new MakeBucketArgs()
.WithBucket(bucketName);
await client.MakeBucketAsync(mbArgs).ConfigureAwait(false);
}
// try
// {
// // 模拟文件上传逻辑
// // 这里可以替换为实际的上传逻辑,例如调用 API 或保存到指定目录
// string destinationPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);
// File.Copy(filePath, destinationPath, overwrite: true);
var progress = new Progress<ProgressReport>(progressReport =>
{
_sendViewModel.Progress = progressReport.Percentage;// 更新进度条的值
});
// // 更新上传时间
// UploadTime = DateTime.Now;
PutObjectArgs putObjectArgs = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName)
.WithFileName(filePath)
//.WithContentType("application/octet-stream")
.WithProgress(progress);
// // 提示上传成功
// MessageBox.Show($"文件 {fileName} 上传成功!", "上传完成", MessageBoxButton.OK, MessageBoxImage.Information);
// }
// catch (Exception ex)
// {
// // 处理上传失败
// MessageBox.Show($"文件上传失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
// }
//}
// 上传文件并提供进度反馈
await client.PutObjectAsync(putObjectArgs);
MessageBox.Show("文件上传成功!");
}
catch (Exception ex)
{
MessageBox.Show($"上传失败: {ex.Message}");
}
}
#endregion

View File

@ -1,6 +1,7 @@
using HeBianGu.Service.Mvc;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Threading;
@ -12,7 +13,7 @@ namespace HeBianGu.App.Disk
protected override void Init()
{
LinkActions.Add(new LinkAction() { Action = "Down", Controller = "Send", DisplayName = "正在下载", Logo = "\xe6f3" });
LinkActions.Add(new LinkAction() { Action = "Down", Controller = "Send", DisplayName = "正在上传", Logo = "\xe6fe" });
LinkActions.Add(new LinkAction() { Action = "UpLoad", Controller = "Send", DisplayName = "正在上传", Logo = "\xe6fe" });
LinkActions.Add(new LinkAction() { Action = "Down", Controller = "Send", DisplayName = "传输完成", Logo = "\xe613" });
LinkActions.Add(new LinkAction() { Action = "Down", Controller = "Send", DisplayName = "文件快传", Logo = "\xe764" });
@ -26,5 +27,29 @@ namespace HeBianGu.App.Disk
protected override void Loaded(string args)
{
}
#region 文件上传
private double _progress;
public double Progress
{
get { return _progress; }
set
{
if (_progress != value)
{
_progress = value;
OnPropertyChanged(nameof(Progress));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}