0

Estoy teniendo problemas en crear un formulario en el cual el usuario rellene un formulario con nombre, apellido y subir un arhivo pdf(en .net core). Busque tutoriales y no se como plantear el problema. De momento logre realizar la carga de archivos pero no puedo agregar a la tabla el nombre y el apellido o no se bien como hacerlo. Si alguien me puede ayudar si se puede hacer en una misma tabla o tengo que crear una tabla persona y otra tabla archivo y relacionarla o como debería enfrentar el problema. Les dejo mi código a continuación.

introducir la descripción de la imagen aquíintroducir la descripción de la imagen aquí introducir la descripción de la imagen aquí introducir la descripción de la imagen aquí

a continuacion les dejo el controlador:

namespace BackendApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileManagerController : Controller
    {
        private readonly string AppDirectory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
        private static List<FileRecord> fileDB = new List<FileRecord>();

        // -------------------- CONTEXT CLASS DECLARATION ------------------------

        private readonly AppDbContext _authContext;
        public FileManagerController (AppDbContext appDbContext)
        {
            _authContext = appDbContext;
        }


        // -------------------- SEND FILES METHOD POST ------------------------

        [HttpPost]
        [Consumes("multipart/form-data")]
        public async Task<HttpResponseMessage> PostAsync([FromForm] FileModel model)
        {
            try
            {
                FileRecord file = await SaveFileAsync(model.MyFile);

                if (!string.IsNullOrEmpty(file.FilePath))
                {
                    file.AltText = model.AltText;
                    file.Description = model.Description;
                    //Save to Inmemory object
                    //fileDB.Add(file);
                    //Save to SQL Server DB
                    SaveToDB(file);
                    return new HttpResponseMessage(HttpStatusCode.OK);
                }
                else
                    return new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(ex.Message),
                };
            }
        }

        private async Task<FileRecord> SaveFileAsync(IFormFile myFile)
        {
            FileRecord file = new FileRecord();
            if (myFile != null)
            {
                if (!Directory.Exists(AppDirectory))
                    Directory.CreateDirectory(AppDirectory);

                var fileName = DateTime.Now.Ticks.ToString() + Path.GetExtension(myFile.FileName);
                var path = Path.Combine(AppDirectory, fileName);

                file.Id = fileDB.Count()+1;
                file.FilePath = path;
                file.FileName = fileName;
                file.FileFormat = Path.GetExtension(myFile.FileName);
                file.ContentType = myFile.ContentType;
                file.AltText = file.AltText;
                file.Description = file.Description;

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await myFile.CopyToAsync(stream);
                }

                return file;
            }
            return file;
        }

        private void SaveToDB(FileRecord record)
        {
            if (record == null)
                throw new ArgumentNullException($"{nameof(record)}");

            FileData fileData = new FileData();
            fileData.FilePath = record.FilePath;
            fileData.FileName = record.FileName;
            fileData.FileExtension = record.FileFormat;
            fileData.MimeType = record.ContentType;

            _authContext.FileDatas.Add(fileData);
            _authContext.SaveChanges();
        }

        // // -------------------- GET ALL FILES  ------------------------

        [HttpGet("getallfiles")]
        public List<FileRecord> GetAllFiles()
        {
            //getting data from inmemory obj
            //return fileDB;
            //getting data from SQL DB
            return _authContext.FileDatas.Select(n => new FileRecord
            {
                Id = n.Id,
                ContentType = n.MimeType,
                FileFormat = n.FileExtension,
                FileName = n.FileName,
                FilePath = n.FilePath
            }).ToList();
        }


        //// -------------------- GET FILES BY ID  ------------------------
        [HttpGet("getallfiles/{id}")]
        public async Task<IActionResult> DownloadFile(int id)
        {
            if (!Directory.Exists(AppDirectory))
                Directory.CreateDirectory(AppDirectory);

            //getting file from inmemory obj
            //var file = fileDB?.Where(n => n.Id == id).FirstOrDefault();
            //getting file from DB
            var file = _authContext.FileDatas.Where(n => n.Id == id).FirstOrDefault();

            var path = Path.Combine(AppDirectory, file?.FilePath);

            var memory = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            var contentType = "APPLICATION/octet-stream";
            var fileName = Path.GetFileName(path);

            return File(memory, contentType, fileName);
        }







    }





}

necesito que cuando una persona se postule a un trabajo pueda cargar su imagen con su nombre y apellido.

3
  • 1
    Hola tomsi, bienvenido, te sugiero que elimines las imagenes y agregues el código como texto, de esa manera evitarás recibir votos negativos y recibirás respuestas, de paso puedes hacer el recorrido de Bienvenida para entender mejor cómo funcionamos y de paso obtener tu primer medalla! el 11 feb. a las 10:25
  • "no puedo agregar a la tabla el nombre y el apellido" porque? queproblemas tuviste? donde te trabaste? que probaste?
    – gbianchi
    el 11 feb. a las 15:38
  • la verdad es que me tira error todo.. hasta al querer agregar las propiedades(nombre,apellido,email) no se a cual de los 3 modelos agregarlo.
    – tomsi
    el 11 feb. a las 16:11

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.