80 lines
2.8 KiB
C#

using Marco.Pms.DataAccess.Data;
using Marco.Pms.Model.Utilities;
using Microsoft.AspNetCore.Mvc;
namespace MarcoBMS.Services.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FileController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment _hostEnvironment;
public FileController(ApplicationDbContext context, IWebHostEnvironment hostEnvironment)
{
_context = context;
_hostEnvironment = hostEnvironment;
}
[HttpPost("fileupload")]
public async Task<IActionResult> FileUploadDemo([FromForm] DemoEmployeeModel model)
{
if(model.ImageFile == null) {return BadRequest(ApiResponse<object>.ErrorResponse("Error.", "Error.", 400));}
string imageName = await Saveimage(model.ImageFile);
return Ok(ApiResponse<object>.SuccessResponse("Success.", "Success.", 200));
}
[NonAction]
public async Task<string> Saveimage(IFormFile file)
{
string imageName = new string(Path.GetFileNameWithoutExtension(file.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yyyymmssfff") + Path.GetExtension(file.FileName);
var imagePath = Path.Combine(_hostEnvironment.ContentRootPath, "images", imageName);
using (var fileStream = new FileStream(imagePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
return imageName;
}
//[HttpPost("manage1")]
//public async Task<IActionResult> CreateUser_1([FromForm] CreateUserDto model)
//{
// if (model == null)
// return BadRequest("Invalid user data.");
// await GetFileDetails(model.Photo);
// return Ok(new { message = "User created successfully. Password reset link sent." });
//}
private static async Task<FileDetails> GetFileDetails(IFormFile file)
{
FileDetails info = new FileDetails();
info.ContentType = file.ContentType;
info.FileName = file.FileName;
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
info.FileData = memoryStream.ToArray();
}
return info;
}
}
public class DemoEmployeeModel
{
public int EmployeeId { get; set; }
public string? EmployeeName { get; set; }
public string? Occupation { get; set; }
public string? ImageName { get; set; }
public string? ImageSrc { get; set; }
public IFormFile? ImageFile { get; set; } // List to handle multiple files
}
}