VS2022 .NET8
💾基础上传示例
view
@{ViewData["Title"] = "File Upload";
}<h1>@ViewData["Title"]</h1><form method="post" enctype="multipart/form-data" action="/Home/UploadFile"><div class="form-group"><input type="file" name="file" class="form-control" /></div><button type="submit" class="btn btn-primary">Upload</button>
</form>
controller
[HttpPost]public async Task<IActionResult> UploadFile(){var file = Request.Form.Files[0];if (file != null && file.Length > 0){var uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "up");if (!Directory.Exists(uploads)){Directory.CreateDirectory(uploads);}var filePath = Path.Combine(uploads, file.FileName);using (var fileStream = new FileStream(filePath, FileMode.Create)){await file.CopyToAsync(fileStream);}// SAVE TO DBreturn RedirectToAction("Index");}return View();}
app.UseStaticFiles();
run
📀优化 限制文件大小
上传文件夹如 img => img rar => file
限制文件大小
// 根据文件类型选择上传的文件夹string fileExtension = Path.GetExtension(file.FileName).ToLower();switch (fileExtension){case ".jpg":case ".png":uploadFolder = Path.Combine("wwwroot", "img");break;case ".mp4":// 检查视频大小是否超过限制if (file.Length > 20 * 1024 * 1024) // 20MB{ModelState.AddModelError("File", "Video file size should not exceed 20MB.");return View("Index", file);}uploadFolder = Path.Combine("wwwroot", "vd");break;case ".m4a":uploadFolder = Path.Combine("wwwroot", "sound");break;case ".rar":uploadFolder = Path.Combine("wwwroot", "file");break;default:ModelState.AddModelError("File", "Unsupported file format.");return View("Index", file);}
🪫删除
view
@model IEnumerable<string><h1>Uploaded Files</h1>@if (Model.Any())
{<table class="table"><thead><tr><th>File Name</th><th>Action</th></tr></thead><tbody>@foreach (var fileName in Model){<tr><td>@fileName</td><td><form method="post" asp-action="DeleteFile"><input type="hidden" name="fileName" value="@fileName" /><button type="submit" class="btn btn-danger">Delete</button></form></td></tr>}</tbody></table>
}
else
{<p>No files uploaded yet.</p>
}
controller
[HttpPost]public IActionResult DeleteFile(string fileName){var uploadFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "img");var filePath = Path.Combine(uploadFolder, fileName);if (System.IO.File.Exists(filePath)){System.IO.File.Delete(filePath);}return RedirectToAction("Files");}
💿️重命名
string fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}{new Random().Next(1000, 9999)}{fileExtension}";var filePath = Path.Combine(uploads, fileName);using (var fileStream = new FileStream(filePath, FileMode.Create)){await file.CopyToAsync(fileStream);}
💽多文件上传
controller
[ApiController][Route("[controller]")]public class FileUploadController : ControllerBase{private readonly string UploadsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "uploads");public FileUploadController(){// 创建上传文件夹(如果不存在)if (!Directory.Exists(UploadsDirectory)){Directory.CreateDirectory(UploadsDirectory);}}[HttpPost][Route("upload")]public async Task<IActionResult> Upload(IFormFile[] files){if (files == null || files.Length == 0){return BadRequest("No files uploaded.");}foreach (var file in files){if (file.Length == 0){return BadRequest($"File {file.FileName} is empty.");}// 根据文件类型选择上传的文件夹string uploadFolder = GetUploadFolder(file.FileName);// 重命名文件为指定格式string fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";string filePath = Path.Combine(UploadsDirectory, uploadFolder, fileName);using (var stream = new FileStream(filePath, FileMode.Create)){await file.CopyToAsync(stream);}// to db}return Ok("Files uploaded successfully.");}private string GetUploadFolder(string fileName){string fileExtension = Path.GetExtension(fileName).ToLower();switch (fileExtension){case ".jpg":case ".png":return "img";case ".mp4":return "vd";case ".m4a":return "sound";case ".rar":return "file";default:throw new NotSupportedException($"Unsupported file format for {fileName}.");}}}
view
@{ViewBag.Title = "File Upload";
}<h2>File Upload2</h2><form id="uploadForm" enctype="multipart/form-data"><input type="file" id="fileInput" multiple><input type="button" value="Upload" onclick="uploadFiles()" />
</form>
<div id="message"></div>@section scripts {<script>function uploadFiles() {var files = document.getElementById('fileInput').files;if (files.length === 0) {showMessage('No files selected.');return;}var formData = new FormData();for (var i = 0; i < files.length; i++) {formData.append('files', files[i]);}$.ajax({url: '@Url.Action("Upload", "FileUpload")',type: 'POST',data: formData,processData: false,contentType: false,success: function (response) {showMessage(response);},error: function (xhr, status, error) {showMessage('Upload failed: ' + error);}});}function showMessage(message) {$('#message').text(message);}</script>
}