.net 文件图片上传接口
[Route("api/[controller]")] public class PicturesController : Controller { private IHostingEnvironment hostingEnv; string[] pictureFormatArray = { "png", "jpg", "jpeg", "bmp", "gif", "ico", "PNG", "JPG", "JPEG", "BMP", "GIF", "ICO" }; public PicturesController(IHostingEnvironment env) { this.hostingEnv = env; } [HttpPost] public IActionResult Post(int isThumbnail,int width,int height) { var controller = Request.Headers[HeaderNames.Referer].ToString().Replace("http://", "").Replace(Request.Host.ToString(), "").Split('/')[1]; var files = Request.Form.Files; long size = files.Sum(f => f.Length); //size > 100MB refuse upload ! if (size > 10485760) { return Json(new Response() { Code = ResponseCode.Success, Message = "上传文件不能超过10MB" }); } var file = files[0]; var fileName = System.Net.Http.Headers.ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); string filePath = hostingEnv.WebRootPath + $@"\upload\Pictures\{controller}\"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string suffix = fileName.Split('.')[1]; if (!pictureFormatArray.Contains(suffix)) { return Json(new Response() { Code = ResponseCode.Success, Message = "只能上传图片格式文件" }); } fileName = Guid.NewGuid() + "." + suffix; string fileFullName = filePath + fileName; if (isThumbnail!=0) { Utils.SaveImageByWidthHeight(width,height, file.OpenReadStream(), fileFullName); } else { using (FileStream fs = System.IO.File.Create(fileFullName)) { file.CopyTo(fs); fs.Flush(); } } //return Json(new Response() { Code = ResponseCode.Success, Message = "上传成功", Value = $"/upload/Pictures/{controller}/{fileName}" }); return Json(new { code = 0, data = new { src = $"/upload/Pictures/{controller}/{fileName}",title= fileName } }); } }
图片压缩方法:引用ZKWeb.System.Drawing
/// <summary> /// 等比例压缩图片 /// </summary> public static void SaveImageByWidthHeight(int intImgCompressWidth, int intImgCompressHeight, Stream stream, string strFileSavePath) { //从输入流中获取上传的image对象 using (Image img = Image.FromStream(stream)) { //根据压缩比例求出图片的宽度 int intWidth = intImgCompressWidth / intImgCompressHeight * img.Height; int intHeight = img.Width * intImgCompressHeight / intImgCompressWidth; //画布 using (Bitmap bitmap = new Bitmap(img, new Size(intImgCompressWidth, intImgCompressHeight))) { //在画布上创建画笔对象 using (Graphics graphics = Graphics.FromImage(bitmap)) { //将图片使用压缩后的宽高,从0,0位置画在画布上 graphics.DrawImage(img, 0, 0, intImgCompressWidth, intImgCompressHeight); //保存图片 bitmap.Save(strFileSavePath); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)