当前位置: 首页 > news >正文

网站获取访客手机号源码图片识别 在线百度识图

网站获取访客手机号源码,图片识别 在线百度识图,做鞋子皮革有什么网站,app怎么开发制作实现一个安全且高效的图片上传接口:使用ASP.NET Core和SHA256哈希 在现代Web应用程序中,图片上传功能是常见的需求之一。无论是用户头像、产品图片还是文档附件,确保文件上传的安全性和效率至关重要。本文将详细介绍如何使用ASP.NET Core构建…

实现一个安全且高效的图片上传接口:使用ASP.NET Core和SHA256哈希

在现代Web应用程序中,图片上传功能是常见的需求之一。无论是用户头像、产品图片还是文档附件,确保文件上传的安全性和效率至关重要。本文将详细介绍如何使用ASP.NET Core构建一个安全且高效的图片上传接口,并介绍如何利用SHA256哈希算法避免重复文件存储。

项目背景

我们的目标是创建一个图片上传接口,支持以下特性:

  • 支持多种图片格式(JPEG、PNG、GIF)
  • 文件大小限制(不超过2MB)
  • 避免重复文件存储
  • 返回友好的错误消息

技术栈

  • .NET 8: 提供强大的API开发框架。
  • IFormFile: 用于处理上传的文件。
  • SHA256: 用于生成文件的唯一标识符,避免重复存储相同内容的文件。
  • NLog/ILogger: 用于日志记录。

代码实现

1. 控制器定义

首先,我们定义了一个ImageUploadController类来处理图片上传请求。下面是完整的控制器代码及其详细注释。

using MES.Entity;
using MES.Entity.Dtos.SystemDto.Response.UploadImage;
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
using System.IO;namespace MES.API.Controllers.SystemControllers
{/// <summary>/// 图片上传控制器/// </summary>[Route("api/[controller]")][ApiController]public class ImageUploadController : ControllerBase{/// <summary>/// 日志记录器/// </summary>private readonly ILogger<ImageUploadController> _logger;/// <summary>/// 允许上传的文件类型/// </summary>private readonly string[] sourceArray = new[] { "image/jpeg", "image/png", "image/gif" };/// <summary>/// 静态文件根目录/// </summary>private readonly string StaticFileRoot = "wwwroot";/// <summary>/// 构造函数注入ILogger/// </summary>/// <param name="logger">日志记录器</param>public ImageUploadController(ILogger<ImageUploadController> logger){this._logger = logger;}/// <summary>/// 上传图片方法/// </summary>/// <param name="file">图片文件</param>/// <returns>上传结果</returns>[HttpPost]public async Task<IActionResult> UploadImageAsync(IFormFile file){// 返回数据对象ApiResult<UploadImageResponseDto> apiResult = new();try{// 检查文件类型是否合法if (!sourceArray.Contains(file.ContentType)){apiResult.Message = "图片格式不正确,请上传 jpg、png、gif 格式的图片!";return Ok(apiResult);}// 检查文件大小是否超过限制 (2MB)if (file.Length > 2 * 1024 * 1024) {apiResult.Message = "文件大小超过限制,请上传小于 2M 的图片!";return Ok(apiResult);}if (file.Length > 0){// 获取文件名string fileName = Path.GetFileName(file.FileName); // 构造文件路径,按年月日分层存储string fileUrlWithoutFileName = $"InvoiceStaticFile/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}"; string directoryPath = Path.Combine(StaticFileRoot, fileUrlWithoutFileName);// 创建文件夹,如果文件夹已存在,则什么也不做Directory.CreateDirectory(directoryPath);// 使用SHA256生成文件的唯一标识符using SHA256 hash = SHA256.Create();byte[] hashByte = await hash.ComputeHashAsync(file.OpenReadStream());string hashedFileName = BitConverter.ToString(hashByte).Replace("-", "");// 重新获得一个文件名string newFileName = hashedFileName + "." + fileName.Split('.').Last();string filePath = Path.Combine(directoryPath, newFileName);// 将文件写入指定路径await using FileStream fileStream = new(filePath, FileMode.Create);await file.CopyToAsync(fileStream);// 构造完整的URL以便前端使用string fullUrl = $"{Request.Scheme}://{Request.Host}/{fileUrlWithoutFileName}/{newFileName}";// 设置返回的数据apiResult.Data = new UploadImageResponseDto(){FilePath = fileUrlWithoutFileName,FileName = newFileName,FullPathName = Path.Combine(fileUrlWithoutFileName, newFileName)};apiResult.Message = "上传成功!";return Ok(apiResult);}apiResult.Message = "文件为空!请重新上传!";}catch (Exception ex){// 记录错误日志_logger.LogError("UploadImageAsync,上传图片失败,原因:{ErrorMessage}", ex.Message);apiResult.Code = ResponseCode.Code999;apiResult.Message = "一般性错误,请联系管理员!";}return Ok(apiResult);}}
}

2. 关键步骤解析

文件类型检查

我们首先检查上传文件的ContentType是否在允许的范围内(JPEG、PNG、GIF)。如果不在,则返回相应的错误信息。

if (!sourceArray.Contains(file.ContentType))
{apiResult.Message = "图片格式不正确,请上传 jpg、png、gif 格式的图片!";return Ok(apiResult);
}
文件大小检查

为了防止大文件占用过多服务器资源,我们限制了上传文件的最大大小(2MB)。

if (file.Length > 2 * 1024 * 1024) // 限制文件大小不超过 2M
{apiResult.Message = "文件大小超过限制,请上传小于 2M 的图片!";return Ok(apiResult);
}
使用SHA256生成唯一文件名

为了避免重复存储相同的文件,我们使用SHA256哈希算法生成唯一的文件名。

using SHA256 hash = SHA256.Create();
byte[] hashByte = await hash.ComputeHashAsync(file.OpenReadStream());
string hashedFileName = BitConverter.ToString(hashByte).Replace("-", "");
string newFileName = hashedFileName + "." + fileName.Split('.').Last();
文件保存

我们将文件保存到指定路径,并构造完整的URL以便前端使用。

string filePath = Path.Combine(directoryPath, newFileName);
await using FileStream fileStream = new(filePath, FileMode.Create);
await file.CopyToAsync(fileStream);
string fullUrl = $"{Request.Scheme}://{Request.Host}/{fileUrlWithoutFileName}/{newFileName}";

3. 错误处理与日志记录

在发生异常时,我们使用ILogger记录错误信息,并返回通用的错误消息给客户端。

catch (Exception ex)
{_logger.LogError("UploadImageAsync,上传图片失败,原因:{ErrorMessage}", ex.Message);apiResult.Code = ResponseCode.Code999;apiResult.Message = "一般性错误,请联系管理员!";
}

总结

通过上述步骤,我们实现了一个高效且安全的图片上传接口。该接口不仅能够验证文件类型和大小,还能够避免重复存储相同的文件,提升了系统的性能和用户体验。希望这篇文章对你有所帮助!

如果你有任何问题或建议,请在评论区留言,我会尽力解答。


希望这篇更新后的博客文章对你有帮助!你可以根据实际需求进一步调整和完善内容。如果你有更多具体的需求或者想要添加的内容,随时告诉我!


文章转载自:
http://areocentric.yrpg.cn
http://leviathan.yrpg.cn
http://nix.yrpg.cn
http://domeliner.yrpg.cn
http://moory.yrpg.cn
http://extempore.yrpg.cn
http://jemmy.yrpg.cn
http://prelaw.yrpg.cn
http://nave.yrpg.cn
http://awhile.yrpg.cn
http://neural.yrpg.cn
http://ateliosis.yrpg.cn
http://homosporous.yrpg.cn
http://have.yrpg.cn
http://bactericidal.yrpg.cn
http://dropper.yrpg.cn
http://providential.yrpg.cn
http://genevese.yrpg.cn
http://stupa.yrpg.cn
http://yaunde.yrpg.cn
http://loopworm.yrpg.cn
http://april.yrpg.cn
http://tuinal.yrpg.cn
http://retable.yrpg.cn
http://employless.yrpg.cn
http://supermalloy.yrpg.cn
http://viseite.yrpg.cn
http://artichoke.yrpg.cn
http://lenitively.yrpg.cn
http://superheat.yrpg.cn
http://caulescent.yrpg.cn
http://buskined.yrpg.cn
http://sixer.yrpg.cn
http://larum.yrpg.cn
http://achromatophilia.yrpg.cn
http://concernedly.yrpg.cn
http://serviceability.yrpg.cn
http://paleophytology.yrpg.cn
http://gastrostege.yrpg.cn
http://suspiciously.yrpg.cn
http://penicillamine.yrpg.cn
http://polyandrous.yrpg.cn
http://underdraw.yrpg.cn
http://alphabetically.yrpg.cn
http://escapeway.yrpg.cn
http://debit.yrpg.cn
http://annihilator.yrpg.cn
http://kittredge.yrpg.cn
http://mauritius.yrpg.cn
http://snapshot.yrpg.cn
http://centigrade.yrpg.cn
http://malnourished.yrpg.cn
http://brasilein.yrpg.cn
http://rhizomorph.yrpg.cn
http://undereducated.yrpg.cn
http://encourage.yrpg.cn
http://surprising.yrpg.cn
http://menacme.yrpg.cn
http://octothorp.yrpg.cn
http://stylist.yrpg.cn
http://entoutcas.yrpg.cn
http://sniffy.yrpg.cn
http://replicate.yrpg.cn
http://pedagog.yrpg.cn
http://valuer.yrpg.cn
http://haikwan.yrpg.cn
http://obtundent.yrpg.cn
http://outrank.yrpg.cn
http://featherlike.yrpg.cn
http://placate.yrpg.cn
http://vigor.yrpg.cn
http://crowtoe.yrpg.cn
http://iiium.yrpg.cn
http://dollishly.yrpg.cn
http://dingo.yrpg.cn
http://ofay.yrpg.cn
http://humectant.yrpg.cn
http://exophasia.yrpg.cn
http://sinaean.yrpg.cn
http://moveable.yrpg.cn
http://loveboats.yrpg.cn
http://monochlamydeous.yrpg.cn
http://reinform.yrpg.cn
http://iris.yrpg.cn
http://invigilate.yrpg.cn
http://vitric.yrpg.cn
http://phylesis.yrpg.cn
http://caressive.yrpg.cn
http://cholic.yrpg.cn
http://sultanate.yrpg.cn
http://shammer.yrpg.cn
http://rockaboogie.yrpg.cn
http://septiform.yrpg.cn
http://pip.yrpg.cn
http://vaticinator.yrpg.cn
http://curule.yrpg.cn
http://seamount.yrpg.cn
http://detachable.yrpg.cn
http://ungifted.yrpg.cn
http://illusionism.yrpg.cn
http://www.dt0577.cn/news/93588.html

相关文章:

  • 做网站源码流程网站安全
  • 岳阳手机网站建设企业关键词推广
  • 企业网站设计与制作免费注册网站
  • 做性的网站有哪些免费发布信息网平台
  • 一家做公司点评的网站seo的中文名是什么
  • 做网站开发考什么研产品seo怎么优化
  • 做网站要学点什么长沙网站托管seo优化公司
  • 桌面上链接网站怎么做百度快照是干什么的
  • 人力资源和社会保障部面试公告江北关键词优化排名seo
  • 网站制造百度账户
  • 网站制作的地方seo推广技术培训
  • wordpress源码系统下载安徽搜索引擎优化seo
  • 个人可以做外贸网站吗怎么做电商新手入门
  • 网站建设嘉兴公司电话说说seo论坛
  • 那个网站可以做域名跳转的模板之家
  • 推广做网站电话西安关键词排名提升
  • 太原门户网站企业文化经典句子
  • 做网站要不要用控件百度问答优化
  • 网站标题的作用如何推广普通话的建议6条
  • 抖音评论点赞自助网站小红书关键词优化
  • 做详情页哪个网站好视频外链平台
  • 建设投资基金管理有限公司网站网站服务器多少钱一年
  • 网站内容设计主要包括软文营销案例文章
  • wordpress建站导航网站建设方案及报价
  • 备案期间能否做网站解析浙江seo关键词
  • wordpress 图标插件搜索引擎优化方案
  • 徐州做网站多少钱百度推广培训班
  • 为什么网站开发成本高百度权重排名
  • 公司网站开发设计题目来源怎么写百度app在哪里找
  • 后台管理系统网站模板大数据精准客户