以下是一个使用Asp.net Core多文件上传到数据库的解决方法,包含代码示例:
public class FileModel
{
public int Id { get; set; }
public string FileName { get; set; }
public byte[] FileData { get; set; }
}
[ApiController]
[Route("api/files")]
public class FileController : ControllerBase
{
private readonly YourDbContext _context;
public FileController(YourDbContext context)
{
_context = context;
}
[HttpPost]
public async Task UploadFiles(List files)
{
foreach (var file in files)
{
if (file.Length > 0)
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
var fileModel = new FileModel
{
FileName = file.FileName,
FileData = memoryStream.ToArray()
};
_context.FileModels.Add(fileModel);
await _context.SaveChangesAsync();
}
}
}
return Ok();
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("YourConnectionString")));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 省略其他配置...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
现在,当你向/api/files路由发送一个多文件上传请求时,它将把文件保存到数据库中。你可以根据需要扩展该方法,例如添加验证、文件类型限制等。