原文地址: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. MySQL之MyISAM和InnoDB

    一.区别 1.MySQL默认采用的是MyISAM. 2.MyISAM不支持事务和外键,而InnoDB支持.InnoDB的AUTOCOMMIT默认是打开的,即每条SQL语句会默认被封装成一个事务,自动提 ...

  2. mysql if--else

    SQL之case when then用法 case具有两种格式.简单case函数和case搜索函数. --简单case函数 case sex when '1' then '男' when '2' th ...

  3. html5验证自适应

    // 移动端跳转 var OS = function() { var a = navigator.userAgent, b = /(?:Android)/.test(a), d = /(?:Firef ...

  4. MySql workbeach 更改侧边栏大小

    1.定位到workbench的样式目录下 cd /usr/share/mysql-workbench/ 2.更改其样式文件 GtkStatusbar GtkLabel { font-size: 12p ...

  5. lftp下载文件无法覆盖,提示" file already existst and xfer:clobber is unset" 问题解决

    在 /etc/lftp.conf   文件中添加以下配置即可 set xfer:clobber on

  6. requestLibrary API

    requestLibrary API Keyword Arguments Documentation Create Ntlm Session alias, url, auth, headers={}, ...

  7. MySQL数据库的库表迁移

    最近在研究MySQL数据库的库表迁移问题,主要分为两种情况,一种情况是迁移数据库的表的全部字段,另一种是迁移数据库的表的部分字段.前一种情况是直接使用mysqldump命令来实现,后一种情况则是采用数 ...

  8. playbook部署coredns

    playbook部署coredns 说明test1是主控节点,目的是给test4 node节点安装coredns, 1.coredns-1.2.2.tar.gz安装包放到主控节点/server/sof ...

  9. elasticsearch的keyword与text的区别

    es2.*用户可忽略该文章.es 2.*版本里面是没有这两个字段!!! 当初接触es,最惊讶就是他的版本速度发布太快,这次主要讨论keyword与text的区别 在es 2.*版本里面是没有这两个字段 ...

  10. 使用青花瓷(charles)抓包

    官网下载charles: https://www.charlesproxy.com/download/ MAC & Apple 打开青花瓷charles 找到本地IP:青花瓷里面Help-&g ...