上一篇
本文目录导读:
🚀 ASP.NET Core 2025年8月更新 | 图片上传功能实现全指南
(信息来源:2025-08-05 .NET官方支持策略 & 2025-07-30 Microsoft Learn文档)
微软刚发布.NET 9的8月补丁(版本9.0.7),重点优化了文件上传的内存管理和安全性能!NET 8(LTS长期支持版)也同步更新,建议开发者优先升级以获得最新安全补丁。
(以ASP.NET Core Web API项目为例)
<form enctype="multipart/form-data" method="post" id="uploadForm"> <input type="file" id="fileInput" accept="image/*" multiple> <button type="submit">上传图片</button> </form>script> document.getElementById('uploadForm').addEventListener('submit', async (e) => { e.preventDefault(); const files = document.getElementById('fileInput').files; const formData = new FormData(); // 分块上传逻辑(支持大文件断点续传) for (let file of files) { const chunkSize = 2 * 1024 * 1024; // 2MB分块 let start = 0, end = chunkSize; const fileName = file.name; while (start < file.size) { const chunk = file.slice(start, end); formData.append('chunk', chunk, `${fileName}_${start}`); formData.append('fileName', fileName); formData.append('totalChunks', Math.ceil(file.size / chunkSize)); await fetch('/api/upload/chunk', { method: 'POST', body: formData }); start = end; end += chunkSize; } } alert('上传完成!'); }); </script>
// Program.cs 配置(.NET 9+) var builder = WebApplication.CreateBuilder(args); builder.Services.Configure<FormOptions>(options => { options.MultipartBodyLengthLimit = 20 * 1024 * 1024; // 20MB总限制 options.MemoryBufferThreshold = 1 * 1024 * 1024; // 1MB后转磁盘缓冲 }); // 文件分块处理API [ApiController] [Route("api/upload")] public class UploadController : ControllerBase { private static readonly Dictionary<string, List<byte[]>> _chunks = new(); [HttpPost("chunk")] public async Task<IActionResult> UploadChunk( [FromForm] byte[] chunk, [FromForm] string fileName, [FromForm] int totalChunks ) { if (!_chunks.ContainsKey(fileName)) { _chunks[fileName] = new List<byte[]>(); } _chunks[fileName].Add(chunk); return Ok($"已接收分块 {_chunks[fileName].Count}/{totalChunks}"); } [HttpPost("merge")] public IActionResult MergeChunks([FromForm] string fileName) { if (!_chunks.ContainsKey(fileName)) return BadRequest("分块不存在"); var fullPath = Path.Combine("wwwroot/uploads", fileName); File.WriteAllBytes(fullPath, _chunks[fileName].SelectMany(c => c).ToArray()); _chunks.Remove(fileName); // 合并后清除缓存 return Ok("文件合并成功!"); } }
1️⃣ 文件类型白名单
var allowedTypes = new[] { ".jpg", ".png", ".webp" }; var ext = Path.GetExtension(file.FileName).ToLower(); if (!allowedTypes.Contains(ext)) throw new InvalidDataException("非法文件类型!");
2️⃣ 防内存爆炸配置
services.Configure<IISServerOptions>(opts => { opts.MaxRequestBodySize = 30 * 1024 * 1024; // IIS环境限制30MB });
3️⃣ 病毒扫描伪代码
using var scanner = new AntiVirusScanner(); if (!scanner.Scan(filePath)) throw new SecurityException("检测到病毒!");
4️⃣ 文件名安全处理
var safeName = Path.GetRandomFileName() + ext; // 生成随机文件名 var savePath = Path.Combine(_env.WebRootPath, "uploads", safeName);
5️⃣ 上传目录隔离
# Linux环境需设置目录权限 chmod 750 /var/www/myapp/uploads chown root:www-data /var/www/myapp/uploads
(以Azure Blob Storage为例)
public async Task UploadToCloud(IFormFile file) { var container = new BlobContainerClient("connStr", "images"); await container.CreateIfNotExistsAsync(); var blob = container.GetBlobClient(file.FileName); await blob.UploadAsync(file.OpenReadStream(), new BlobHttpHeaders { ContentType = file.ContentType }); }
await file.CopyToAsync(stream)
) Path.GetRandomFileName()
替代原始文件名 🔥 立即测试你的上传功能:
dotnet new webapi -n FileUploadDemo cd FileUploadDemo dotnet run --urls http://localhost:5000
(本文代码兼容.NET 8/9,实际部署需根据服务器环境调整路径和权限设置)
本文由 业务大全 于2025-08-23发表在【云服务器提供商】,文中图片由(业务大全)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vds.7tqx.com/wenda/703424.html
发表评论