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 @   MTony  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
点击右上角即可分享
微信分享提示