Maui Blazor Windows 显示本地图片新方法更简单快速 支持.Net 8.0 最新版本

目前仅Windows平台测试,安卓平台暂不支持,调用

AppDomain.CurrentDomain.BaseDirectory,直接储存图片到wwwroot里的images文件夹内,在razor里直接使用<img src="images/图片路径" />即可
        private void SetAvarta()
        {
            MainThread.BeginInvokeOnMainThread(async () =>
            {
                FileResult? photo = await MediaPicker.Default.PickPhotoAsync(new MediaPickerOptions
                {
                    Title = "选择头像"
                });
                if (photo != null)
                {
                    string UserAvatarPath = "Avatar";
                    string photoName = Guid.NewGuid().ToString() + Path.GetExtension(photo.FileName);
                    string localFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "images", UserAvatarPath, photoName);

                    // 确保目录存在
                    Directory.CreateDirectory(Path.GetDirectoryName(localFilePath) ?? string.Empty);
                    // 保存文件到本地存储
                    using Stream sourceStream = await photo.OpenReadAsync();
                    using FileStream localFileStream = File.Create(localFilePath);

                    await sourceStream.CopyToAsync(localFileStream);

                    Debug.WriteLine($"File saved to: {localFilePath}");
                }
            });
        }

 

posted @ 2024-08-28 18:31  MTony  阅读(24)  评论(0编辑  收藏  举报