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 ?