示例#1
0
        public async Task <HttpResponseMessage> Upload()
        {
            // Verifica se request contém multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            //Diretório App_Data, para salvar o arquivo temporariamente
            string root     = HttpContext.Current.Server.MapPath("~/App_Data");
            var    provider = new MultipartFormDataStreamProvider(root);

            // Lê o arquivo da requisição assincronamente
            await Request.Content.ReadAsMultipartAsync(provider);

            ICollection <Aluno> alunos = null;

            // Para cada arquivo enviado
            foreach (MultipartFileData file in provider.FileData)
            {
                try
                {
                    //Importa o arquivo
                    alunos = _importacaoService.Importar(file.LocalFileName, provider.FormData["nomeArquivo"]);
                }
                catch (CPFNaoInformadoException e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(MessagesResource.CPFNaoInformado, e.IndexAluno)));
                }
                catch (CPFFormatoIncorretoException e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(MessagesResource.CPFInvalido, e.IndexAluno, e.CPF)));
                }
                catch (NomeNaoInformadoException e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(MessagesResource.NomeNaoInformado, e.IndexAluno, e.CPF)));
                }
                catch (EnderecoNaoInformadoException e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(MessagesResource.EnderecoNaoInformado, e.IndexAluno, e.CPF)));
                }
                catch (InvalidOperationException e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message + ' ' + e.InnerException.Message));
                }
                catch (Exception e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message));
                }
            }
            return(Request.CreateResponse(HttpStatusCode.OK, alunos));
        }
        public async Task <IActionResult> Importar(IFormFile file)
        {
            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream).ConfigureAwait(false);

                var errosImportacao = await _importacaoService.Importar(memoryStream);

                if (errosImportacao.Any())
                {
                    return(BadRequest(errosImportacao));
                }
            }
            return(Ok());
        }