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
    }

posted @ 2019-04-03 15:28  94cool  阅读(3259)  评论(0编辑  收藏  举报