博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Upload Image to .NET Core 2.1 API
阅读量:5242 次
发布时间:2019-06-14

本文共 6263 字,大约阅读时间需要 20 分钟。

原文地址:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ImageWriter.Helper{    public class WriterHelper    {        public enum ImageFormat        {            bmp,            jpeg,            gif,            tiff,            png,            unknown        }        public static ImageFormat GetImageFormat(byte[] bytes)        {            var bmp = Encoding.ASCII.GetBytes("BM");     // BMP            var gif = Encoding.ASCII.GetBytes("GIF");    // GIF            var png = new byte[] { 137, 80, 78, 71 };              // PNG            var tiff = new byte[] { 73, 73, 42 };                  // TIFF            var tiff2 = new byte[] { 77, 77, 42 };                 // TIFF            var jpeg = new byte[] { 255, 216, 255, 224 };          // jpeg            var jpeg2 = new byte[] { 255, 216, 255, 225 };         // jpeg canon            if (bmp.SequenceEqual(bytes.Take(bmp.Length)))                return ImageFormat.bmp;            if (gif.SequenceEqual(bytes.Take(gif.Length)))                return ImageFormat.gif;            if (png.SequenceEqual(bytes.Take(png.Length)))                return ImageFormat.png;            if (tiff.SequenceEqual(bytes.Take(tiff.Length)))                return ImageFormat.tiff;            if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))                return ImageFormat.tiff;            if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))                return ImageFormat.jpeg;            if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))                return ImageFormat.jpeg;            return ImageFormat.unknown;        }    }}

 IImageWriter.cs 

using Microsoft.AspNetCore.Http;using System.Threading.Tasks;namespace ImageWriter.Interface{    public interface IImageWriter    {        Task
UploadImage(IFormFile file); }}
using System;using System.Collections.Generic;using System.IO;using System.Text;using System.Threading.Tasks;using ImageWriter.Helper;using ImageWriter.Interface;using Microsoft.AspNetCore.Http;namespace ImageWriter.Classes{    public class ImageWriter : IImageWriter    {        public async Task
UploadImage(IFormFile file) { if (CheckIfImageFile(file)) { return await WriteFile(file); } return "Invalid image file"; } ///
/// Method to check if file is image file /// ///
///
private bool CheckIfImageFile(IFormFile file) { byte[] fileBytes; using (var ms = new MemoryStream()) { file.CopyTo(ms); fileBytes = ms.ToArray(); } return WriterHelper.GetImageFormat(fileBytes) != WriterHelper.ImageFormat.unknown; } ///
/// Method to write file onto the disk /// ///
///
public async Task
WriteFile(IFormFile file) { string fileName; try { var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1]; fileName = Guid.NewGuid().ToString() + extension; //Create a new Name //for the file due to security reasons. var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", fileName); using (var bits = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(bits); } } catch (Exception e) { return e.Message; } return fileName; } }}
using System.Threading.Tasks;using ImageWriter.Interface;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace ImageUploader.Handler{    public interface IImageHandler    {        Task
UploadImage(IFormFile file); } public class ImageHandler : IImageHandler { private readonly IImageWriter _imageWriter; public ImageHandler(IImageWriter imageWriter) { _imageWriter = imageWriter; } public async Task
UploadImage(IFormFile file) { var result = await _imageWriter.UploadImage(file); return new ObjectResult(result); } }}
using System.Threading.Tasks;using ImageUploader.Handler;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace ImageUploader.Controllers{    [Route("api/image")]    public class ImagesController : Controller    {        private readonly IImageHandler _imageHandler;        public ImagesController(IImageHandler imageHandler)        {            _imageHandler = imageHandler;        }        ///         /// Uplaods an image to the server.        ///         ///         /// 
public async Task
UploadImage(IFormFile file) { return await _imageHandler.UploadImage(file); } }}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)        {            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            else            {                app.UseHsts();            }            //Use this to set path of files outside the wwwroot folder            //app.UseStaticFiles(new StaticFileOptions            //{            //    FileProvider = new PhysicalFileProvider(            //        Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),            //    RequestPath = "/StaticFiles"            //});            app.UseStaticFiles(); //letting the application know that we need access to wwwroot folder.            app.UseHttpsRedirection();            app.UseMvc();        }// This method gets called by the runtime. Use this method to add services to the container.        public void ConfigureServices(IServiceCollection services)        {            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);            services.AddTransient
(); services.AddTransient
(); }

 

转载于:https://www.cnblogs.com/YrRoom/p/11108227.html

你可能感兴趣的文章
day22 01 初识面向对象----简单的人狗大战小游戏
查看>>
mybatis源代码分析:深入了解mybatis延迟加载机制
查看>>
Flask三剑客
查看>>
Hibernate-缓存
查看>>
【BZOJ4516】生成魔咒(后缀自动机)
查看>>
提高PHP性能的10条建议
查看>>
svn“Previous operation has not finished; run 'cleanup' if it was interrupted“报错的解决方法...
查看>>
熟用TableView
查看>>
Java大数——a^b + b^a
查看>>
poj 3164 最小树形图(朱刘算法)
查看>>
服务器内存泄露 , 重启后恢复问题解决方案
查看>>
android一些细节问题
查看>>
KDESVN中commit时出现containing working copy admin area is missing错误提示
查看>>
利用AOP写2PC框架(二)
查看>>
【动态规划】skiing
查看>>
java定时器的使用(Timer)
查看>>
ef codefirst VS里修改数据表结构后更新到数据库
查看>>
boost 同步定时器
查看>>
[ROS] Chinese MOOC || Chapter-4.4 Action
查看>>
简单的数据库操作
查看>>