原文地址:https://www.codeproject.com/Articles/1256591/Upload-Image-to-NET-Core-2-1-API

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[] { , , , }; // PNG
var tiff = new byte[] { , , }; // TIFF
var tiff2 = new byte[] { , , }; // TIFF
var jpeg = new byte[] { , , , }; // jpeg
var jpeg2 = new byte[] { , , , }; // 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<string> 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<string> UploadImage(IFormFile file)
{
if (CheckIfImageFile(file))
{
return await WriteFile(file);
} return "Invalid image file";
} /// <summary>
/// Method to check if file is image file
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
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;
} /// <summary>
/// Method to write file onto the disk
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public async Task<string> WriteFile(IFormFile file)
{
string fileName;
try
{
var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - ];
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<IActionResult> UploadImage(IFormFile file);
} public class ImageHandler : IImageHandler
{
private readonly IImageWriter _imageWriter;
public ImageHandler(IImageWriter imageWriter)
{
_imageWriter = imageWriter;
} public async Task<IActionResult> 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;
} /// <summary>
/// Uplaods an image to the server.
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public async Task<IActionResult> 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<IImageHandler, ImageHandler>();
services.AddTransient<ImageWriter.Interface.IImageWriter,
ImageWriter.Classes.ImageWriter>();
}

Upload Image to .NET Core 2.1 API的更多相关文章

  1. File upload in ASP.NET Core web API

    参考1:File upload in ASP.NET Core web API https://www.janaks.com.np/file-upload-asp-net-core-web-api/ ...

  2. 使用.NET Core在RESTful API中进行路由操作

    介绍 当列出REST API的最佳实践时,Routing(路由)总是使它位于堆栈的顶部.今天,在这篇文章中,我们将使用特定于.NET Core的REST(web)API来处理路由概念. 对于新手API ...

  3. .Net Core中的Api版本控制

    原文链接:API Versioning in .Net Core 作者:Neel Bhatt 简介 Api的版本控制是Api开发中经常遇到的问题, 在大部分中大型项目都需要使用到Api的版本控制 在本 ...

  4. 【转】.Net Core中的Api版本控制

    原文链接:API Versioning in .Net Core 作者:Neel Bhatt 简介 Api的版本控制是Api开发中经常遇到的问题, 在大部分中大型项目都需要使用到Api的版本控制 在本 ...

  5. 如何使用 Core Plot 的 API 帮助文档

    Core Plot 可是 iOS 下绝好的图表组件,虽说它的相关资料不甚丰富,特别是中文的,英文的还是有几篇不错的文章,不过 Core Plot 自身提供的 API 帮助文档,以及代码示例其实很有用的 ...

  6. 从零开始搭建.NET Core 2.0 API(学习笔记一)

    从零开始搭建.NET Core 2.0 API(学习笔记一) 一. VS 2017 新建一个项目 选择ASP.NET Core Web应用程序,再选择Web API,选择ASP.NET Core 2. ...

  7. angular4和asp.net core 2 web api

    angular4和asp.net core 2 web api 这是一篇学习笔记. angular 5 正式版都快出了, 不过主要是性能升级. 我认为angular 4还是很适合企业的, 就像.net ...

  8. ASP.NET Core 中基于 API Key 对私有 Web API 进行保护

    这两天遇到一个应用场景,需要对内网调用的部分 web api 进行安全保护,只允许请求头账户包含指定 key 的客户端进行调用.在网上找到一篇英文博文 ASP.NET Core - Protect y ...

  9. ASP.NET Core WebApi构建API接口服务实战演练

    一.ASP.NET Core WebApi课程介绍 人生苦短,我用.NET Core!提到Api接口,一般会想到以前用到的WebService和WCF服务,这三个技术都是用来创建服务接口,只不过Web ...

随机推荐

  1. How to delete System Profiles for those registered with Red Hat Subscription Management (RHSM)?

    Environment Red Hat Customer Portal Certificate Based Subscription Red Hat Subscription Management ( ...

  2. [Mybatis]执行一句Sql返回一个List<String>

    在Mapper.xml如下书写SQL文,其中 resultType告知MyBatis返回的类型: <select id="selectExpiredDate" resultT ...

  3. Selenium 2自动化测试实战40(单线程)

    单线程 #onethread.py #coding:utf-8 from time import sleep,ctime #听音乐任务 def music(): print('i was listen ...

  4. java IO流的API

    常用的IO流API有:[InputStream.OutputStream] [FileInputStream.FileOutputStream] [BufferedInputStream.Buffer ...

  5. 错误 MSB6006 CL.exe 已退出,代码为2

    环境 WIN10 + VS2019 社区版 按照其他网友的方法说 解决方法: 1 一个类内部的定义返回类型为double的方法种没有写return语句. 2 变量没有初始化也会导致这种情况. 但是设置 ...

  6. TypeScript01 编译环境的搭建、字符串特性、类型特性

    知识准备:JavaScript满足ES5前端规范.TypeScript满足ES6前端规范 1 TypeScript开发环境 TypeScript代码不能直接被浏览器识别,必须先转换成JS代码:通常是利 ...

  7. 解读Vue.use()源码

    Vue.use() vue.use()的作用: 官方文档的解释: 安装 Vue.js 插件.如果插件是一个对象,必须提供 install 方法.如果插件是一个函数,它会被作为 install 方法.i ...

  8. PTA --- L1-006 连续因子

    题目地址 一个正整数 N 的因子中可能存在若干连续的数字.例如 630 可以分解为 3×5×6×7,其中 5.6.7 就是 3 个连续的数字.给定任一正整数 N,要求编写程序求出最长连续因子的个数,并 ...

  9. 快速搭建WordPress博客

    博主在看了朋友的博客后 决定也搭建一个wordPress 博客 思路 1.购买服务器 2.Cenots环境配置 3.安装wordpress 工具 推荐使用 Xshell 6,当然也可以用其他 服务器推 ...

  10. SpringCloud学习(八)消息总线(Spring Cloud Bus)(Finchley版本)

    Spring Cloud Bus 将分布式的节点用轻量的消息代理连接起来.它可以用于广播配置文件的更改或者服务之间的通讯,也可以用于监控.本文要讲述的是用Spring Cloud Bus实现通知微服务 ...