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 ...
随机推荐
- Nginx数据结构之散列表
1. 散列表(即哈希表概念) 散列表是根据元素的关键码值而直接进行访问的数据结构.也就是说,它通过把关键码值映射到表中一个位置来访问记录, 以加快查找速度.这个映射函数 f 叫做散列方法,存放记录的数 ...
- 【软件工程】Alpha事后诸葛亮
链接部分 队名:女生都队 组长博客: 博客链接 作业博客:博客链接 参考邹欣老师的问题模板进行总结思考 一.设想和目标 1.我们的软件要解决什么问题?是否定义得很清楚?是否对典型用户和典型场景有清晰的 ...
- python之ActionChains方法列表
使用方法: 方法列表: click(on_element=None) ——单击鼠标左键 click_and_hold(on_element=None) ——点击鼠标左键,不松开 context_cli ...
- koa 实现下载文件
文件下载需要使用到koa-send这个插件,该插件是一个静态文件服务的中间件,它可以用来实现文件下载的功能. 1.下载页面 static/download.html <!DOCTYPE html ...
- linux下如何更新当前的容器镜像?
docker commit <container_id> <container_image_name>
- 【Linux命令】find命令
[find命令] 说明:find命令用来在指定目录下查找文件.任何位于参数之前的字符串都将被视为欲查找的目录名.如果使用该命令时,不设置任何参数,则find命令将在当前目录下查找子目录与文件.并且将查 ...
- bind绑定服务的生命周期
bindService(service, conn, flags); * service :意图 * conn :activity和服务的连接通道 * flags : BIND_AUTO_CREATE ...
- Linux下的C的开发之GCC的初级使用
<span style="font-family: Arial, Helvetica, sans-serif; "><span style="white ...
- Linux命令集锦:tmux命令
tmux是一款优秀的终端复用软件,平时用到的强大功能有下面两个: 窗口管理:同时启用多个窗口: 保护现场:连接到远程主机之后,一旦断开,那么当前账户登录的任务就被取消了,但是使用 tmux 可以在断开 ...
- js如何控制select展开
找了一圈也没找到靠谱的方案,后来通过动态的控制select的size属性实现了. 这也算是一种方法吧. 先判断option的数量n,然后把select的size调整到n,当用户选择后,再把size设置 ...