分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

.net core使用ViewComponent将页面图片转码成base64

发布时间:2023-09-06 02:34责任编辑:傅花花关键词:base64
 using System;using System.IO;using System.Threading.Tasks;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Caching.Memory;namespace MyPorject.MVC.ViewComponents{ ???public class ImgToBase64ViewComponent : ViewComponent ???{ ???????private readonly IHostingEnvironment _hostingEnvironment; ???????private readonly IMemoryCache _memoryCache; ???????public ImgToBase64ViewComponent(IHostingEnvironment hostingEnvironment, IMemoryCache memoryCache) ???????{ ???????????_hostingEnvironment = hostingEnvironment; ???????????_memoryCache = memoryCache; ???????} ???????public async Task InvokeAsync(string src) ???????{ ???????????string cacheKey = src; ???????????string result = await _memoryCache.GetOrCreateAsync(cacheKey, async entry => ?????????????{ ?????????????????string webRootPath = _hostingEnvironment.WebRootPath; ?????????????????string path = webRootPath + @"\" + src.TrimStart(‘~‘).TrimStart(‘/‘).Replace(@"/", @"\").ToString(); ?????????????????try ?????????????????{ ?????????????????????using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) ?????????????????????{ ?????????????????????????var byteArray = new byte[fs.Length]; ?????????????????????????await fs.ReadAsync(byteArray, 0, byteArray.Length); ?????????????????????????result = "data:image/jpeg;base64," + Convert.ToBase64String(byteArray); ?????????????????????} ?????????????????} ?????????????????catch (Exception ex) ?????????????????{ ?????????????????????result = ex.Message; ?????????????????} ?????????????????return await Task.FromResult(result); ?????????????}); ???????????return View("", result); ???????} ???}}

 添加default.cshtml

 使用方法:

将原来src中改成Component.InvokeAsync 就可以使用了

 效果如图:

.net core使用ViewComponent将页面图片转码成base64

原文地址:https://www.cnblogs.com/WNpursue/p/10447208.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved