当前位置: 首页 > news >正文

c# webapi上传、读取、删除图片

public class FileAPIController : BaseController
    {
        private readonly string prefix = "thumb_";
        private readonly Token token;
        private readonly ServiceImpl.Config.AppConfig config;
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="token"></param>
        /// <param name="config"></param>
        public FileAPIController(Token token, ServiceImpl.Config.AppConfig config)
        {
            this.config = config;
            this.token = token;
            if (token == null)
            {
                throw new ApiException(HttpStatusCode.Unauthorized, "用户登录已过期!");
            }
        }

        #region 上传文件

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="subpath">文件子目录</param>
        /// <param name="thumbnail">缩略图大小,格式:width*height,为空不生成缩略图</param>
        /// <returns></returns>
        [HttpPost]
        [Route("v1/file/{subpath}")]
        public async Task<IEnumerable<string>> Upload(string subpath = null, string thumbnail = null)
        {
            if (token == null || token.EntCode == null)
            {
                throw new ApiException(HttpStatusCode.Unauthorized, "用户登录已过期!");
            }
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            List<string> files = new List<string>();
            try
            {
                MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);

                #region 文件目录

                string root = GetRoot(subpath, string.Empty);
                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }

                #endregion

                foreach (HttpContent file in provider.Contents)
                {
                    string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    byte[] buffer = await file.ReadAsByteArrayAsync();

                    string savename = Guid.NewGuid().ToString("N");

                    string uploadFileName = $"{savename}{Path.GetExtension(filename)}";

                    string filePath = $"{root}\\{uploadFileName}";

                    File.WriteAllBytes(filePath, buffer);

                    files.Add($"{(string.IsNullOrWhiteSpace(subpath) ? "" : $"{subpath}\\")}{uploadFileName}");

                    #region 是否生成缩略图

                    if (!string.IsNullOrWhiteSpace(thumbnail) && new Regex(@"\d+\*\d+").IsMatch(thumbnail))
                    {
                        int width = int.Parse(thumbnail.Split('*')[0]);
                        int height = int.Parse(thumbnail.Split('*')[1]);
                        if (width < 1)
                        {
                            width = 100;
                        }

                        if (height < 1)
                        {
                            height = 100;
                        }

                        string thumbnailPath = $"{root}\\{prefix}{savename}.png";
                        MakeThumbnail(filePath, thumbnailPath, width, height);
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                log.Error($"上传文件出错", ex);
            }

            return files;
        }

        #endregion

        #region 上传文件

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="subpath">子目录</param>
        /// <param name="filename">文件名称</param>
        /// <param name="thumbnail">true=输出缩略图,false=输出原图</param>
        /// <returns></returns>
        [HttpGet]
        [Route("v1/file/{subpath}/{filename}")]
        public async Task<HttpResponseMessage> Get(string subpath, string filename, bool thumbnail = true)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "无效参数");
            }

            #region 文件名解密

            string name = filename.Substring(0, filename.LastIndexOf('.'));
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "无效参数");
            }

            #endregion

            try
            {
                string path = GetRoot(subpath, thumbnail ? $"{prefix}{name}.png" : filename);
                if (File.Exists(path))
                {
                    FileStream stream = new FileStream(path, FileMode.Open);

                    HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StreamContent(stream)
                    };
                    resp.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = Path.GetFileName(path)
                    };
                    string contentType = MimeMapping.GetMimeMapping(path);
                    resp.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    resp.Content.Headers.ContentLength = stream.Length;

                    return await Task.FromResult(resp);
                }
            }
            catch (Exception ex)
            {
                if (log != null)
                {
                    log.Error($"下载文件出错:{token}", ex);
                }
            }
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }

        #endregion

        #region 删除文件

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="subpath">子目录</param>
        /// <param name="filename">文件名称</param>
        /// <returns></returns>
        [HttpDelete]
        [Route("v1/file/{subpath}/{filename}")]
        public bool Delete(string subpath, string filename)
        {
            if (token == null || token.EntCode == null)
            {
                throw new ApiException(HttpStatusCode.Unauthorized, "用户登录已过期!");
            }
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "无效参数");
            }
            bool result = true;
            try
            {
                string path = GetRoot(subpath, filename);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            catch (Exception ex)
            {
                log.Error($"删除文件出错:{subpath}/{filename}", ex);
                result = false;
            }
            try
            {
                string name = filename.Substring(0, filename.LastIndexOf('.'));
                string thumbnailPath = GetRoot(subpath, $"{prefix}{name}.png");
                if (File.Exists(thumbnailPath))
                {
                    File.Delete(thumbnailPath);
                }
            }
            catch (Exception ex)
            {
                log.Error($"删除缩略图出错:{subpath}/{filename}", ex);
            }
            return result;
        }

        #endregion

        #region 文件目录

        /// <summary>
        /// 文件目录
        /// </summary>
        /// <param name="subpath">文件子目录</param>
        /// <param name="filename">文件名称</param>
        /// <returns></returns>
        private string GetRoot(string subpath, string filename)
        {
            #region 文件目录

            string appName = AppConfig.Default.AppName;
            string fileDir = config.UploadRoot;
            if (string.IsNullOrWhiteSpace(fileDir) || string.IsNullOrWhiteSpace(Path.GetDirectoryName(fileDir)))
            {
                fileDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload");
            }
            return Path.Combine(fileDir, appName, subpath, filename);

            #endregion
        }

        #endregion

        #region 生成缩略图

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>   
        private void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height)
        {
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            if (originalImage.Width / (double)originalImage.Height > towidth / (double)toheight)
            {
                ow = originalImage.Width;
                oh = originalImage.Width * height / towidth;
                x = 0;
                y = (originalImage.Height - oh) / 2;
            }
            else
            {
                oh = originalImage.Height;
                ow = originalImage.Height * towidth / toheight;
                y = 0;
                x = (originalImage.Width - ow) / 2;
            }

            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.Clear(Color.Transparent);
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
            try
            {
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        #endregion
    }

转载于:https://www.cnblogs.com/94cool/p/10649155.html

相关文章:

  • JAVA面向对象的总结(函数重载与数组)
  • CUBA Studio 9.0 发布 ,企业级应用开发平台
  • Maven 的这 7 个问题你思考过没有?
  • Maven 运行启动时****找不到符号*com.xxx.user.java
  • win10子系统 (linux for windows)打造python, pytorch开发环境
  • 美团全链路压测自动化实践
  • 现代密码学知识图谱
  • 盘点几个在手机上可以用来学习编程的软件
  • 1 RAC解析 自定义链式编程
  • Cacti 1.2.3 发布,网络流量监测图形分析工具
  • ASP.NET MVC 使用过滤器需要注意
  • Toolbar SearchView的用法
  • 微信小程序video组件层级
  • Node.js 应用故障排查手册 —— 综合性 GC 问题和优化
  • MySQL高性能优化规范建议
  • 【翻译】Mashape是如何管理15000个API和微服务的(三)
  • 【挥舞JS】JS实现继承,封装一个extends方法
  • CSS魔法堂:Absolute Positioning就这个样
  • CSS实用技巧干货
  • Fastjson的基本使用方法大全
  • HTTP那些事
  • iOS 颜色设置看我就够了
  • Javascripit类型转换比较那点事儿,双等号(==)
  • JS基础篇--通过JS生成由字母与数字组合的随机字符串
  • leetcode378. Kth Smallest Element in a Sorted Matrix
  • leetcode46 Permutation 排列组合
  • Puppeteer:浏览器控制器
  • Spring技术内幕笔记(2):Spring MVC 与 Web
  • ViewService——一种保证客户端与服务端同步的方法
  • windows下如何用phpstorm同步测试服务器
  • 看完九篇字体系列的文章,你还觉得我是在说字体?
  • 如何邀请好友注册您的网站(模拟百度网盘)
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • #AngularJS#$sce.trustAsResourceUrl
  • #单片机(TB6600驱动42步进电机)
  • ${factoryList }后面有空格不影响
  • $forceUpdate()函数
  • (+3)1.3敏捷宣言与敏捷过程的特点
  • (3)nginx 配置(nginx.conf)
  • (二)hibernate配置管理
  • (附源码)springboot助农电商系统 毕业设计 081919
  • (附源码)ssm航空客运订票系统 毕业设计 141612
  • (一)Linux+Windows下安装ffmpeg
  • (原創) 物件導向與老子思想 (OO)
  • .Net Framework 4.x 程序到底运行在哪个 CLR 版本之上
  • .net framework4与其client profile版本的区别
  • .NET 程序如何获取图片的宽高(框架自带多种方法的不同性能)
  • .NET 反射的使用
  • .one4-V-XXXXXXXX勒索病毒数据怎么处理|数据解密恢复
  • @Autowired多个相同类型bean装配问题
  • []新浪博客如何插入代码(其他博客应该也可以)
  • [20170705]diff比较执行结果的内容.txt
  • [android] 看博客学习hashCode()和equals()
  • [Android]竖直滑动选择器WheelView的实现