原文地址: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. typescript简单的应用

    简单来说typescript就是新增一下方法,以及增加类型判断 一.普通的类型判断 1.布尔类型(boolean) let isDone: boolean = false let createdByB ...

  2. 487-3279 字符串处理+MAP

    487-3279 Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 300264   Accepted: 53757 Descr ...

  3. WordPress窗体化侧边栏

    窗体化侧边栏是一个支持 Widget 的侧边栏或者说是窗体化(widgetized)的侧边栏几乎是 WordPress 主题的标准. 首先,什么是窗体化(widgetizing)呢?简单的说,窗体化就 ...

  4. springboot 底层 JackSon 的使用

    Jackson常用的注解使用和使用场景: 接下来我们在看一段代码,这段代码是常用注解在实体类User中的简单使用:package zone.reborn.springbootstudy.entity; ...

  5. LC 980. Unique Paths III

    On a 2-dimensional grid, there are 4 types of squares: 1 represents the starting square.  There is e ...

  6. 使用Fiddler抓取在夜神模拟器上的请求

    一.设置Fiddler代理 1.点击Tools-Fiddler Options进入Fiddler Options页面 2.点击Connections,将Fiddler listens on port设 ...

  7. springmvc集成swagger

    1.保证项目为maven项目 2.导入jar包依赖 <dependency> <groupId>io.springfox</groupId> <artifac ...

  8. redis 超时失效key 的监听触发使用

    redis自2.8.0之后版本提供Keyspace Notifications功能,允许客户订阅Pub / Sub频道,以便以某种方式接收影响Redis数据集的事件. 可能收到的事件的例子如下: 所有 ...

  9. Java NIO学习笔记九 NIO与IO对比

    Java NIO与IO Java nio 和io 到底有什么区别,以及什么时候使用nio和io,本文做一个比较. Java NIO和IO之间的主要区别 下表总结了Java NIO和IO之间的主要区别, ...

  10. Ubuntu开放指定端口

    一般情况下,ubuntu安装好的时候,iptables会被安装上,如果没有的话那就安装上吧 安装 在终端输入 sudo apt-get install iptables 添加规则 在终端输入 ipta ...