public ActionResult SubirArchivo(IFormFile file) { string urlImagenNueva = string.Empty; ResponseProductoImportarDtoApi respuesta = new ResponseProductoImportarDtoApi { StatusCode = 400, ListaError = new List <ErrorDtoApi>() }; try { if (file == null) { respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = "El archivo no ha sido cargado" }); return(BadRequest(respuesta)); } string idNegocio = string.Empty; string idMoneda = string.Empty; string idCategoria = string.Empty; try { idNegocio = Request.Form["IdNegocio"][0]; idMoneda = Request.Form["IdMoneda"][0]; idCategoria = Request.Form["IdCategoria"][0]; if (idNegocio == "0") { respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = "Seleccione el negocio" }); } if (idMoneda == "0") { respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = "Seleccione la moneda" }); } if (idCategoria == "0") { respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = "Seleccione la categoria" }); } if (respuesta.ListaError.Any()) { respuesta.StatusCode = 400; return(BadRequest(respuesta)); } } catch { respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = "Seleccione el negocio" }); return(BadRequest(respuesta)); } if (file.Length == 0) { respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = "El archivo no ha sido cargado" }); return(BadRequest(respuesta)); } bool esError = false; if (idNegocio == null) { esError = true; } if (idNegocio == "0") { esError = true; } if (Request.Form.Files == null) { esError = true; } if (!Entidad.Utilitario.Util.EsLong(idNegocio)) { esError = true; } if (!esError) { var nombreArchivo = System.Net.Http.Headers.ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); string extension = Path.GetExtension(nombreArchivo).Trim().Replace(".", string.Empty).ToLower(); if (extension != "xlsx") { respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = "Solo se admiten archivos .xlsx" }); return(BadRequest(respuesta)); } byte[] archivoBytes; using (var memoryStream = new MemoryStream()) { file.CopyTo(memoryStream); archivoBytes = memoryStream.ToArray(); } if (archivoBytes != null) { //ResponseProductoImportarDtoApi RequestProductoImportarDtoApi prmApi = new RequestProductoImportarDtoApi { IdNegocio = Convert.ToInt64(idNegocio), ExtensionSinPunto = extension, ArchivoBytes = archivoBytes, IdCategoria = Convert.ToInt32(idCategoria), IdMoneda = Convert.ToInt32(idMoneda) }; var t = Task.Run(() => _lnProducto.Importar(prmApi)); t.Wait(); if (t.Result != null) { respuesta = t.Result; } } } else { //Error en los parametros respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = "Parametros incompletos para continuar con el proceso" }); return(BadRequest(respuesta)); } } catch (InvalidOperationException invEx) { string mensajeInvEx = (string.IsNullOrEmpty(invEx.StackTrace) ? invEx.Message : invEx.StackTrace).Replace(Environment.NewLine, " "); Logger.Log(Logger.Level.Error, mensajeInvEx); respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = string.Format("[InvalidOperationException]{0}", mensajeInvEx) }); return(BadRequest(respuesta)); } catch (Exception ex) { string mensajeEx = (ex.InnerException == null ? ex.Message : ex.InnerException.Message).Replace(Environment.NewLine, " "); Logger.Log(Logger.Level.Error, mensajeEx); respuesta.ListaError.Add(new ErrorDtoApi { Mensaje = string.Format("[Exception]{0}", mensajeEx) }); return(BadRequest(respuesta)); } if (respuesta.StatusCode == 400) { return(BadRequest(respuesta)); } if (respuesta.ListaError.Any()) { respuesta.StatusCode = 400; return(BadRequest(respuesta)); } respuesta.StatusCode = 200; return(Ok(respuesta)); }
public async Task <ResponseProductoImportarDtoApi> Importar(RequestProductoImportarDtoApi prm) { ResponseProductoImportarDtoApi resultado = new ResponseProductoImportarDtoApi(); int statusCode = 400; try { XLWorkbook libro; using (Stream stream = new MemoryStream(prm.ArchivoBytes)) { libro = new XLWorkbook(stream); } List <string> listaValidacionEstructura = new List <string>(); bool validacion = false; if (libro != null) { if (ValidarEstructuraExcel(libro, ref listaValidacionEstructura)) { //Validar fila por fila validacion = ValidarDataExcel(libro, ref listaValidacionEstructura); } } //solo debe continuar si la data es valida if (validacion) { //Dentro de AJAX => datatype: 'json', headers: {'Authorization': 'Basic ' + valor token }, .... var response = string.Empty; string url = string.Format("{0}{1}/Importar", ConstanteVo.UrlBaseApi, _nombreControlador); using (var client = new HttpClient()) { if (ConstanteVo.ActivarLLamadasConToken && !string.IsNullOrEmpty(ConfiguracionToken.ConfigToken)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ConfiguracionToken.ConfigToken.Trim()); } var content = new StringContent(JsonConvert.SerializeObject(prm), Encoding.UTF8, "application/json"); HttpResponseMessage result = await client.PostAsync(new Uri(url), content); if (result != null) { response = await result.Content.ReadAsStringAsync(); statusCode = (int)result.StatusCode; } } if (!string.IsNullOrEmpty(response)) { resultado = new ResponseProductoImportarDtoApi(); resultado = JsonConvert.DeserializeObject <ResponseProductoImportarDtoApi>(response); } } else { List <ErrorDtoApi> ListaErrorValidacion = new List <ErrorDtoApi>(); foreach (var itemValidacion in listaValidacionEstructura) { ListaErrorValidacion.Add(new ErrorDtoApi { Mensaje = itemValidacion }); } resultado.ListaError = ListaErrorValidacion; resultado.StatusCode = statusCode; } } catch (Exception ex) { if (resultado == null) { resultado = new ResponseProductoImportarDtoApi(); } if (resultado.ListaError == null) { resultado.ListaError = new List <ErrorDtoApi>(); } string exMessage = (ex.InnerException == null ? ex.Message : ex.InnerException.Message).Replace(Environment.NewLine, " "); Log(Level.Error, exMessage); resultado.ListaError.Add(new ErrorDtoApi { Mensaje = exMessage }); } finally { if (resultado != null) { resultado.StatusCode = statusCode; } } return(resultado); }