Abp小试牛刀之 图片上传

图片上传是很常见的功能,里面有些固定的操作也可以沉淀下来。
本文记录使用Abp vNext做图片上传的姿势。

本文的技术核心不在Abp,Abp只是手段!

目标

  1. 上传图片----->预览图片----->确定保存
  2. 支持集群部署

实现思路:

① 上传图片要使用WebAPI特定媒体类型:multipart/form-data;
② 因为要做图片预览,故在上传时利用AbpCache做一个临时缓存,返回图片Id
③ 前端利用FileReader渲染预览图;
④ [确定]: 发起持久化WebAPI(利用第②步返回的图片Id)

为什么强调支持集群部署?

就这个功能而言,[上传预览]和[确定保存]是两次Http WebAPI请求。

如果服务端使用的是Redis等进程外缓存: 那这正好是一个Stateless应用功能,集群环境次功能无惧!

如果服务端使用的是进程内缓存:在集群环境,前后两次请求有可能打到不同的App服务,后置的[确定保存]WebAPI因此可能报错, 此处需要做 [会话亲和性] Session affinity

实践

利用Abp做图片上传

IFormFile能力如下红框:

下面将图片二进制流转化为 base64字符串,注入Abp缓存组件IDistributedCache<string>
缓存图片字符串1小时。

[上传预览], [确定保存]的API完整代码如下:

/// <summary>
       /// 上传预览, 返回待上传的图片id,Content-Type:multipart/form-data
       /// </summary>
       /// <returns></returns>
       [Consumes("multipart/form-data")]
       [Route("upload/preview")]
       [ProducesResponseType(typeof(Guid),200)]
       [HttpPost]
       public async Task<Guid> UploadPicPreviewAsync(IFormFile uploadedFile)
       {
           var formFileName = uploadedFile.FileName;
           if (!new[] { ".png", ".jpg", ".bmp" }.Any((item) => formFileName.EndsWith(item)))
           {
               throw new AbpValidationException("您上传的文件格式必须为png、jpg、bmp中的一种");
           }
           byte[] bytes;
           using (var bodyStream = uploadedFile.OpenReadStream())
           {
               using (var m = new MemoryStream())
               {
                   await bodyStream.CopyToAsync(m);
                   bytes = m.ToArray();
               }
           }
           string base64 = Convert.ToBase64String(bytes);
           var bgId = Guid.NewGuid();
           _cache.Set($"{CurrentUser.TenantId}:bg:{bgId}", base64, new DistributedCacheEntryOptions { SlidingExpiration = new TimeSpan(1, 0, 0) });
           return bgId;
       }
       
       /// <summary>
       /// 保存图片,要使用到前置API的预览图片id
       /// </summary>
       /// <param name="createPictureInput"></param>
       /// <returns></returns>
       [Route("upload/")]
       [HttpPost]
       public async Task<bool> UploadPicAsync([FromBody] CreatePictureInput createPictureInput)
       {
           var based64 = await _cache.GetAsync($"{CurrentUser.TenantId}:bg:{createPictureInput.PreviewPicId}");
           if (string.IsNullOrEmpty(based64))
               throw  new AbpException("Cache Hotmap Picture do not find");

           var model = ObjectMapper.Map<CreatePictureInput, Picture>(createPictureInput);
           model.ProfileId = CurrentUser.TenantId;
           model.BlobStorage = Convert.FromBase64String(based64);
           return await _pictures.InsertAsync(model)!= null;
       }

切记: 上传图片使用 MIME, 同时在webAPI注意,IFormFile的形参名称uploadedFile 一定要与 前端传入的filename 一样,否则无法绑定。

Default implementation of the IDistributedCache interface is the MemoryDistributedCache which works in-memory.
The Distributed Memory Cache (AddDistributedMemoryCache) is a framework-provided implementation of IDistributedCache that stores items in memory. The Distributed Memory Cache isn't an actual distributed cache. Cached items are stored by the app instance on the server where the app is running.

以上两段文字来自 Abp和Asp.NETCore官方文档:

  1. Abp默认的IDistributedCache实现是分布式内存缓存;
  2. ASP.NETCore 分布式内存缓存是框架内置的,是一个假的分布式缓存,实际是单纯的内存缓存。

在没有使用真实分布式缓存的情况下, 需要对前后两个API配置会话亲和性。

会话亲和性

下面从nginx、Azure、k8s ingress 三角度配置[会话亲和性],(全站生效)
会话亲和性的实现原理,是在接受客户端首次请求时响应某个cookie,服务器会认定使用同一个cookie的请求为一个会话。

1. nginx

属于nginx负载均衡的范畴:https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/

示例如下:

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    sticky cookie srv_id expires=1h domain=.example.com path=/;
}
2. Azure App Service

Azure pp Service是Azure云平台提供的App托管服务,具备多实例自动缩放的能力,
其有关会话亲和性的配置如图:

3. K8S nginx-ingress

注解nginx.ingress.kubernetes.io/affinity在入口的所有上游中启用和设置亲和性类型。
这样,请求将总是被定向到相同的上游服务器。

https://kubernetes.github.io/ingress-nginx/examples/affinity/cookie/

That's All

本文以常见的图片上传功能为例,实战演练了Abp的缓存和持久化能力;
引申出对有状态应用配置会话亲和性,部署方式要结合业务功能。

希望对大家有所帮助!

posted @ 2020-12-27 18:30  博客猿马甲哥  阅读(1044)  评论(1编辑  收藏  举报