S3 Amazon com Java - resolvido

package br.com.ghnetsoft.s3amazon.service;

import static org.apache.commons.lang3.StringUtils.isEmpty;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.S3ObjectSummary;

import br.com.ghnetsoft.s3amazon.dto.ArquivoDTO;
import br.com.ghnetsoft.s3amazon.exception.GeralException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class S3AmazonService implements Serializable {

	private static final long serialVersionUID = -8430710375947645965L;
	@Value("${amazon.login}")
	private String usuario;
	@Value("${amazon.senha}")
	private String senha;
	@Value("${amazon.bucket}")
	private String bucket;

	public void salvar(MultipartFile file) {
		try {
			String[] separarArquivo = file.getOriginalFilename().split(".");
			if (separarArquivo.length > 1) {
				throw new GeralException("Nome do arquivo deve ter somente um ponto !");
			}
			AmazonS3 s3 = credentials();
			final String extensao = buscarExtensao(file.getContentType());
			final File novoArquivo = File.createTempFile("s3amazon_", extensao);
			final FileOutputStream fos = new FileOutputStream(novoArquivo);
			fos.write(file.getBytes());
			s3.putObject(bucket, file.getOriginalFilename(), novoArquivo);
			fos.close();
		} catch (AmazonServiceException | IOException e) {
			log.error(e.getMessage(), e);
			throw new GeralException("Erro em salvar arquivo do servidor de arquivos !");
		}
	}

	public ArquivoDTO buscar(String nome) {
		try {
			String[] separarArquivo = validacaoExcluirBuscar(nome);
			String extensao = buscarExtensao(separarArquivo[1]);
			S3Object s3object = credentials().getObject(bucket, nome);
			S3ObjectInputStream inputStream = s3object.getObjectContent();
            File novoArquivo = File.createTempFile("s3_", extensao);
			FileUtils.copyInputStreamToFile(inputStream, novoArquivo);
			
			
			return ArquivoDTO.builder()
					.arquivo(null)
					.contentType(extensao)
					.nome(nome)
					.tamanho(novoArquivo.getTotalSpace())
					.build();
			
		} catch (IOException | AmazonServiceException e) {
			log.error(e.getMessage(), e);
			throw new GeralException("Erro em buscar arquivodo servidor de arquivos !");
		}
	}

	private String[] validacaoExcluirBuscar(String nome) {
		if (isEmpty(nome)) {
			throw new GeralException("Nome do arquivo deve estar preenchido !");
		}
		String[] separarArquivo = nome.split("\\.");
		if (separarArquivo.length < 1) {
			throw new GeralException("Nome do arquivo está inválido !");
		}
		return separarArquivo;
	}

	private AmazonS3 credentials() {
		try {
			return AmazonS3ClientBuilder.standard()
					.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(usuario, senha)))
					.withRegion(Regions.US_EAST_2).build();
		} catch (AmazonServiceException e) {
			log.error(e.getMessage(), e);
			throw new GeralException("Erro ao conectar no servidor de arquivos !");
		}
	}

	private String buscarExtensao(final String extensaoArquivo) {
		String extensao = ".pdf";
		if ("IMAGE/BMP".equalsIgnoreCase(extensaoArquivo)) {
			extensao = ".bmp";
		} else if ("IMAGE/PNG".equalsIgnoreCase(extensaoArquivo.toUpperCase())) {
			extensao = ".png";
		} else if ("IMAGE/JPEG".equalsIgnoreCase(extensaoArquivo.toUpperCase())) {
			extensao = ".jpeg";
		} else if ("IMAGE/JPG".equalsIgnoreCase(extensaoArquivo.toUpperCase())) {
			extensao = ".jpg";
		} else if ("application/vnd.ms-Excel".equalsIgnoreCase(extensaoArquivo.toUpperCase())) {
			extensao = ".xlsx";
		}
		return extensao;
	}
}

Agora ele está enviando o arquivo para o S3. Mas quando faço donwload, está vazio.

O erro pode estar no upload ou no donwload ?

O que é estar vazio?

null? notFound? String vazia?


Te aconselho a fazer assim (isso me ajuda mt pelo menos), baixa o AWS CLI, e faz o teste procurando o objeto via linha de comando, exemplo:

aws s3 ls s3://nome_bucker/pasta/outra_pasta/mais_outra_pasta/

Se for printado algum item na pasta que vc escolher, é pq fez o upload certinho;
agora se não vier nada, nem vou upado.


Se vier, pega o nome certinho do arquivo que vc upou e marreta ele como string mesmo, coloca o nome do arquivo e procura pelo java. Se funcionar, o download ta certo

1 curtida

Não entendi

Baixa o AWS CLI.


Vc já fez algum upload lá no S3 dentro de algum bucket, certo?

Se sim, roda esse comando abaixo:

aws s3 ls s3://nome_bucket/

e mostra pra a gente o que apareceu na sua tela.

1 curtida

Como faço isso ?

Só tenho acesso vi JAvA

Vc tem esses dados?

AWS Access Key ID
AWS Secret Access Key
region
1 curtida

Tenho

Show. Agora baixa o AWS CLI de acordo com seu OS.

Nem pediu as chaves

Acho que foi vacilo meu

Fiz um novo teste e está buscando sim