Bom dia!
Estou fazendo um upload de imagem usando ajax, que chama o controller e o mesmo retorna a resposta através do json.
No Chromium esta ok, mas no FireFox qdo é para retorna o json abre uma janela de download, para salvar a imagem
Alguém poderia me ajudar nesse problema.
Abaixo segue os códigos
- CÓDIGO DO AJAX
<script type="text/javascript" >
$(function(){
var urlAction = '<c:url value="/clippings/uploadImage/"/>';
//var fileImage = '${webAddress.type.imageLogo}' + "_" + '${webAddress.id}' + ".png";
//var fileImage = "aa.png";
new AjaxUpload($('#botao_enviar_arquivo'), //botao que var permitir o usuário escolher o arquivo
{
action: urlAction, //nome do script que vai tratar a requisição enviando o arquivo
name: 'imagem', //nome do campo de arquivo do form que vai ser enviado, no php vai o arquivo vai ser acessado como $_FILES['arquivo']
dataType: 'json',//esta funcao do onSubmit é chamada antes do arquivo ser enviado então é possível fazer verificações e validações.
onSubmit: function(arquivo, extensao){ //arquivo é o nome do arquivo e extensao sua extensao
if (! (extensao && /^(jpg|png|jpeg|gif)$/.test(extensao))){
//neste if acima estamos fazendo uma verificao para enviar somente imagens
//mas o ideal é fazer esta verificação no servidor também
$('#mensagem').html('Somente imagens podem ser enviadas.');
return false; //se retornar false o upload nao é feito
}
$('#mensagem').html('<img style="margin-top: 15px;" src="<c:url value="/images/loading.gif"/>" />');
},
//esta funcao od onComplete é chamada depois que o upload é feito
onComplete: function(arquivo, resposta){ //arquivo é o nome do arquivo enviado, resposta é a resposta do servidor
//dando um replace no nome da thumb de resposta do upload
thumbNewFileImage = resposta;
alert("thumbNewFileImage: "+thumbNewFileImage);
thumbNewFileImage = thumbNewFileImage.replace('<pre style="word-wrap: break-word; white-space: pre-wrap;">{"thumbFileImage": "', "");
thumbNewFileImage = thumbNewFileImage.replace('"}</pre>', "");
//dando um replace no nome da resposta do upload
NewFileImage = thumbNewFileImage;
NewFileImage = NewFileImage.replace('thumb_', "");
//a resposta do servidor não pode ser uma string igual a "FALSE"
$('#mensagem').html('');//limpa a div de mensagem
//se reposta for igual a sucesso é só exibir a imagem usando o nome dela.
var src = '<c:url value="/images/clippings/" />' + thumbNewFileImage + "?" + new Date().getTime();
//var src = 'http://192.168.10.61:8080/images/clippings/' + thumbNewFileImage + "?" + new Date().getTime();
var conteudo_imagem = '<li>';
conteudo_imagem += '<img src="' + src + '"/>';
conteudo_imagem += '</li>';
conteudo_imagem += '<input type="hidden" name="clipping.thumbnail" value="' + thumbNewFileImage +'"/>';
conteudo_imagem += '<input type="hidden" name="clipping.image" value="' + NewFileImage +'"/>';
$('#arquivos').html(conteudo_imagem);
},
onError: function() {
alert("error");
}
});
});
</script>
- CONROLLER
public void uploadImage(UploadedFile imagem) {
UUID uuid = UUID.randomUUID();
String thumbFileImage = "thumb_"+uuid+".png";
String fileImage = uuid+".png";
System.out.println("fileImage: "+fileImage);
if (imagem != null) {
try {
//String filePath = imagesPath + "/logo_url.png";
String filePath = imagesPath + "/" + thumbFileImage;
System.out.println("filePath: "+filePath);
File file = new File(filePath);
//file.deleteOnExit();
if (!file.exists()) file.createNewFile();
Image image = ImageIO.read(imagem.getFile());
int width = image.getWidth(null);
int height = image.getHeight(null);
if (height > MAX_HEIGHT) {
System.out.println("--------1---------width: "+width);
System.out.println("--------1---------height: "+height);
width = MAX_HEIGHT * width / height;
height = MAX_HEIGHT;
System.out.println("--------2---------width: "+width);
System.out.println("--------2---------height: "+height);
image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
}
if (width > MAX_WIDTH) {
height = MAX_WIDTH * height / width;
width = MAX_WIDTH;
image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
}
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
ImageIO.write(bufferedImage, "png" , file);
} catch (FileNotFoundException e) {
e.printStackTrace();
//throw new FileNotFoundException("Arquivo não encontrado!");
} catch (IOException e) {
e.printStackTrace();
//throw new IOException("Não foi possível enviar o arquivo!");
}
}
System.out.println("thumbFileImage: "+thumbFileImage);
result.use(json()).from(thumbFileImage, "thumbFileImage").serialize(); //ACHO QUE O PROBLEMA ESTA AKI...
}