Upload Image to .NET Core 2.1 API
原文地址: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的更多相关文章
- 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/ ...
- 使用.NET Core在RESTful API中进行路由操作
介绍 当列出REST API的最佳实践时,Routing(路由)总是使它位于堆栈的顶部.今天,在这篇文章中,我们将使用特定于.NET Core的REST(web)API来处理路由概念. 对于新手API ...
- .Net Core中的Api版本控制
原文链接:API Versioning in .Net Core 作者:Neel Bhatt 简介 Api的版本控制是Api开发中经常遇到的问题, 在大部分中大型项目都需要使用到Api的版本控制 在本 ...
- 【转】.Net Core中的Api版本控制
原文链接:API Versioning in .Net Core 作者:Neel Bhatt 简介 Api的版本控制是Api开发中经常遇到的问题, 在大部分中大型项目都需要使用到Api的版本控制 在本 ...
- 如何使用 Core Plot 的 API 帮助文档
Core Plot 可是 iOS 下绝好的图表组件,虽说它的相关资料不甚丰富,特别是中文的,英文的还是有几篇不错的文章,不过 Core Plot 自身提供的 API 帮助文档,以及代码示例其实很有用的 ...
- 从零开始搭建.NET Core 2.0 API(学习笔记一)
从零开始搭建.NET Core 2.0 API(学习笔记一) 一. VS 2017 新建一个项目 选择ASP.NET Core Web应用程序,再选择Web API,选择ASP.NET Core 2. ...
- angular4和asp.net core 2 web api
angular4和asp.net core 2 web api 这是一篇学习笔记. angular 5 正式版都快出了, 不过主要是性能升级. 我认为angular 4还是很适合企业的, 就像.net ...
- ASP.NET Core 中基于 API Key 对私有 Web API 进行保护
这两天遇到一个应用场景,需要对内网调用的部分 web api 进行安全保护,只允许请求头账户包含指定 key 的客户端进行调用.在网上找到一篇英文博文 ASP.NET Core - Protect y ...
- ASP.NET Core WebApi构建API接口服务实战演练
一.ASP.NET Core WebApi课程介绍 人生苦短,我用.NET Core!提到Api接口,一般会想到以前用到的WebService和WCF服务,这三个技术都是用来创建服务接口,只不过Web ...
随机推荐
- Mac下持续集成-查看占用的端口及kill
(base) localhost:~ ligaijiang$ lsof -i tcp:8080 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Q ...
- 【Webscraper】不懂编程也能爬虫
一.配置环境 在浏览器中安装web scraper插件. 所有安装包下载链接: https://pan.baidu.com/s/1CfAWf0wMO6WqicoUgdYgkg 提取码: nn2e 安装 ...
- MySQL5.7 创建及查看数据库
1.创建数据库语句create database语句是在MySQL实例上创建一个指定名称的数据库.create schema语句的语义和create database是一样的. 2.语法解析 CREA ...
- 3.ibatis4种事务类型浅析
ibatis中Transaction有四个实现类 其中spring的SqlMapClientFactoryBean类中 private Class transactionConfigClass = E ...
- kotlin之类构造器
Kotlin中类允许定义个主构造器和多个第二构造器. 主构造器就是类头的一部分,紧跟在类名的后面,构造器参数是可选的 package loaderman import loaderman.bar.Pe ...
- NLP基础
1 自然语言处理三大特征抽取器(CNN/RNN/TF)比较 白衣骑士Transformer:盖世英雄站上舞台 华山论剑:三大特征抽取器比较 综合排名情况 以上介绍内容是从几个不同角度来对RNN/CN ...
- 哈希算法MD5和SHA1的C#实现
/* * 哈希算法MD5和SHA1的C#实现 * * * 夏春涛 Email:xChuntao@163.com * Blog:http://bluesky521.cnblogs.com * 运行 ...
- python 粘包现象
一. 粘包现象 1. 粘包现象的由来(1)TCP属于长连接,当服务端与一个客户端进行了连接以后,其他客户端需要(排队)等待.若服务端想要连接另一个客户端,必须首先断开与第一个客户端的连接. (2)缓冲 ...
- Unity热更新 AssetBundle
在游戏开发中,常常需要用到热更新技术.比如:一个手机游戏开发好后,用户安装到手机上.如果此时我们要更新一个新的功能,如果没有热更新,那么需要用户卸载掉手机上的游戏,然后安装新的包,这样做十分麻烦,而且 ...
- Leetcode之动态规划(DP)专题-309. 最佳买卖股票时机含冷冻期(Best Time to Buy and Sell Stock with Cooldown)
Leetcode之动态规划(DP)专题-309. 最佳买卖股票时机含冷冻期(Best Time to Buy and Sell Stock with Cooldown) 股票问题: 121. 买卖股票 ...