E ai galera blz,
Consegui fazer mais ou menos o que eu queria…
como na máquina do cliente eu não tenho permisão estou enviando o objeto Icon do JLabel.
No lado do server eu tenho dois tratamentos de upload, um para Objeto e outro para arquivo.
Isso eu identifico quando na URL, creio q deva ter alguma forma automática de fazer essa identificação, mas eu já pesquisei demais de ontem pra hoje, e resolvi apelar mesmo, segue abaixo o código caso alguém precise:
Parametro tipo=ST : Webstart (estou recebendo um objeto)
Parametro tipo=WB : Web (Estou recebendo um arquivo)
Lado do cliente - Html
Aqui é só uma página o único detalhe é o tipo do formulário e do campo
[code]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Send File - Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
</head>
<body>
<form name="form1" method="post"
action="…/hdesk.sendFile?tipo=WB"
enctype="multipart/form-data">
<input name="filename" type="file">
<input type="submit" name="btnEnviar" value="Enviar">
</form>
</body>
</html>[/code]
Lado do cliente - Webstart
Método que envia o arquivo, o resto é um JFrame convencional
[code]
public void UploadImage() {
try {
//Atribui a url do servlet para fazer o upload
String path = "http://localhost:8080/myApp/hdesk.sendFile?tipo=WB";
URL url = new URL(path);
URLConnection conn = url.openConnection();
//Prepara a conexão para Entrada e Saída
conn.setDoInput(true);
conn.setDoOutput(true);
//Desabilita o Cache
conn.setUseCaches(false);
//Atribui o content type
conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
//Escreve o objeto como post
ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
// Pega o Icon do JLabel
out.writeObject(lblImage.getIcon());
out.flush();
out.close();
// Envia o arquivo
InputStream ins = conn.getInputStream();
ObjectInputStream objin = new ObjectInputStream(ins);
// Aguarda o retorno
String msg = (String)objin.readObject();
JOptionPane.showMessageDialog(this, "Arquivo gravado com sucesso.");
System.exit(0);
} catch (Exception e) {
e.PrintStackTrace();
}
}[/code]
Lado do Server - Servlet Comum
No metodo doPost identifico qual o tipo do envio se é Obj ou não.
Arqui utilizei o commons-FileUpload da Jakarta para fazer o upload de arquivos
http://jakarta.apache.org/commons/fileupload/
[code]public class UploadTicketFile extends HttpServlet {
…
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Carrega o tipo do post
String tp = request.getParameter("tipo");
//Verica o tipo do post:
//tipo=ST : Webstart (estou recebendo um objeto)
//tipo=WB : Web (Estou recebendo um arquivo)
if (tp != null && tp.equals("ST")) {
//tipo ST chama o método para upload de objeto
uploadObj(request, response);
}
else {
PrintWriter out = null;
try {
response.setContentType("text/plain");
out = response.getWriter();
//Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();
//set the max uploaded file size (-1 for no max size)
upload.setSizeMax(-1);
//Parse the request
List items = upload.parseRequest(request);
int loopcnt = 0;
//Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
loopcnt++;
FileItem item = (FileItem) iter.next();
if (item.isFormField()) { // the item is not a file item
String fieldname = item.getFieldName();
String value = item.getString();
out.println(
"RESULT=OK\n" +
"MSG=Arquivo enviado com sucesso.\n" +
"ERROR="
);
} else { //the item is a file item
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
//copy the file to disk
File uploadedFile = new File(fileName);
item.write(uploadedFile);
} //end of if - else
} //end of while
} catch (Exception e){
out.println(
"RESULT=FAIL\n" +
"MSG=Ocorreu um erro fatal no envio do arquivo.\n"+
"ERROR="+e.getMessage()
);
}
}
}
//Upload do Objeto Imagem
private void uploadObj(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
//Carrega o objeto enviado no request
ObjectInputStream objin = new ObjectInputStream(request.getInputStream());
try {
// Converte o objeto para um image Icon
ImageIcon icon = (ImageIcon)objin.readObject();
Image img = icon.getImage();
// Atribui o tipo da Imagem e
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.drawImage(img, null, null);
FileOutputStream fout = null;
//Change it to some server specific path
String fileName = "ticketImage.jpg";
fout = new FileOutputStream(fileName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fout);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(0.5f, false);
encoder.setJPEGEncodeParam(param);
try {
encoder.encode(bi);
fout.close();
// Envia um objeto com informando o resultado da operação
ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
out.writeObject(
"RESULT=OK\n" +
"MSG=Arquivo enviado com sucesso.\n" +
"ERROR="
);
out.flush();
out.close();
}
catch (java.io.IOException io) {}
} catch (Exception e) {}
}
…
}[/code]