在.NET Core中将文件上传到指定路径涉及几个基础概念和技术点,包括文件上传处理、文件存储、安全性考虑以及错误处理。以下是详细的解答:
以下是一个简单的.NET Core控制器示例,演示如何处理文件上传并将其保存到指定路径:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
[Route("api/[controller]")]
[ApiController]
public class FileUploadController : ControllerBase
{
private readonly string _uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
[HttpPost]
public IActionResult UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file selected.");
if (!Directory.Exists(_uploadPath))
{
Directory.CreateDirectory(_uploadPath);
}
var filePath = Path.Combine(_uploadPath, file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok(new { message = "File uploaded successfully." });
}
}
appsettings.json
来增加这个限制。{
"Kestrel": {
"Limits": {
"MaxRequestBodySize": 10485760 // 10MB
}
}
}
if (!file.ContentType.StartsWith("image/"))
{
return BadRequest("Invalid file type.");
}
请注意,实际部署时,还需要考虑更多的安全性和性能优化措施。
领取专属 10元无门槛券
手把手带您无忧上云