66 lines
2.2 KiB
C#
66 lines
2.2 KiB
C#
using FamilyTreeAPI.Entities;
|
|
using FamilyTreeAPI.Repository;
|
|
|
|
namespace FamilyTreeAPI.Controllers;
|
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System.IO;
|
|
using System.Threading.Tasks;
|
|
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
public class FileUploadController : ControllerBase
|
|
{
|
|
private readonly IWebHostEnvironment _hostingEnvironment;
|
|
private readonly ImportPersonRepository _importPersonRepository;
|
|
public FileUploadController(IWebHostEnvironment hostingEnvironment, ImportPersonRepository importPersonRepository)
|
|
{
|
|
_hostingEnvironment = hostingEnvironment;
|
|
_importPersonRepository = importPersonRepository;
|
|
}
|
|
|
|
[HttpPost("UploadFile")]
|
|
public async Task<IActionResult> UploadFile(IFormFile file)
|
|
{
|
|
List<CodeDto<string>> output = new ();
|
|
if (file == null || file.Length == 0)
|
|
{
|
|
return BadRequest("No file uploaded.");
|
|
}
|
|
|
|
try
|
|
{
|
|
// Define the upload directory
|
|
// var uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
|
|
var uploadsFolder = Path.Combine(_hostingEnvironment.ContentRootPath, "uploads");
|
|
if (!Directory.Exists(uploadsFolder))
|
|
{
|
|
Directory.CreateDirectory(uploadsFolder);
|
|
}
|
|
|
|
// Create a unique file name to avoid overwriting
|
|
var uniqueFileName = Path.GetFileNameWithoutExtension(file.FileName)
|
|
+ "_" + System.Guid.NewGuid().ToString()
|
|
+ Path.GetExtension(file.FileName);
|
|
var filePath = Path.Combine(uploadsFolder, uniqueFileName);
|
|
|
|
// Save the file to the server
|
|
using (var stream = new FileStream(filePath, FileMode.Create))
|
|
{
|
|
// await file.CopyToAsync(stream);
|
|
await file.CopyToAsync(stream);
|
|
output = await _importPersonRepository.ImportPerson(stream, "Sheet1");
|
|
|
|
}
|
|
|
|
//return Ok(new { FileName = uniqueFileName, FilePath = filePath });
|
|
return Ok(output);
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
return StatusCode(500, $"Internal server error: {ex.Message}");
|
|
}
|
|
}
|
|
}
|