Olá pessoal, ontem precisei fazer um download de arquivo, no VRaptor isso é bem simples, como o arquivo que eu tinha estava salvo no banco como byte[] eu tinha duas opções transformar o meu array de bytes em File ou InputStream.
Como eu não quereia fazer nenhum dos dois, e sei que tem a possibilidade de mandar diretamente o byte[] para download num OutputStream, então eu criei essa classe utilitária implementando Download:import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import br.com.caelum.vraptor.interceptor.download.Download;
public class ByteArrayDownload implements Download {
private final byte[] byteArray;
private final String contentType;
private final String fileName;
private final boolean doDownload;
private final long size;
public ByteArrayDownload(byte[] byteArray, String contentType){
this(byteArray, contentType, null, false, 0);
}
public ByteArrayDownload(byte[] byteArray, String contentType, boolean doDownload){
this(byteArray, contentType, null, doDownload, 0);
}
public ByteArrayDownload(byte[] byteArray, String contentType, String fileName, boolean doDownload, long size) {
super();
this.byteArray = byteArray;
this.contentType = contentType;
this.fileName = fileName;
this.doDownload = doDownload;
this.size = size;
}
@Override
public void write(HttpServletResponse response) throws IOException {
writeDetails(response);
OutputStream out = response.getOutputStream();
IOUtils.write(byteArray, out);
}
void writeDetails(HttpServletResponse response) {
if(fileName != null){
String contentDisposition = String.format("%s; filename=%s", doDownload ? "attachment" : "inline", fileName);
response.setHeader("Content-disposition", contentDisposition);
}
if (contentType != null) {
response.setHeader("Content-type", contentType);
}
if (size > 0) {
response.setHeader("Content-Length", Long.toString(size));
}
}
}
Ela é quase uma cópia da classe InputStreamDownload, que esta no core do VRaptor.
Espero que sirva pra alguém, porque pra mim já me ajudou em pelo menos duas situações.