天天看點

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