Oi Bulinha, Oi Pessoal ...
 
 Eu implementei aqui o transmissor e funciona muito bem para o que eu
preciso aqui que � transmitir dados at� no m�ximo 1 MB . Mais fazendo
alguns testes , eu percebi que arquivos acima de 12 MB ele n�o
consegue transmitir , d� um erro no momento do envio, exatamente na
linha 89 (BufferedInputStream bi = new
BufferedInputStream(urlConn.getInputStream());) .

-------------------------------------------------- ERRO
-------------------------------------------------
java.io.IOException: Server returned HTTP response code: 500 for URL:
http://sede-1385.datasus.gov:8084/SIOPS/Snet_Serv
        at 
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1133)
--------------------------------------------------------------------------------------------------------------

Eu fiz alguma altera��es no c�digo para suportar um ProgressBar, mais
o resto continua o mesmo .. segue os fontes em anexo . (formul�rio,
cliente e servidor).

Abra�os,
-=|FRED|=-
   




On 5/10/05, Frederico Werly Julio da Silva
<[EMAIL PROTECTED]> wrote:
>  
>   
> -----Mensagem original-----
> De: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]
> Enviada em: quarta-feira, 23 de mar�o de 2005 18:28
> Para: [email protected]
> Assunto: Re: [JUG-Petro] RES: [riojug] Enviando Arquivos com Aplica��o Swing
> 
> 
> 
> Frederico, esta ai atachado o codigo do programa para enviar o arquivo via
> http e o codigo da servlet pra receber o arquivo e salvar (to salvando no
> c:\).
> 
> enviaArquivo.java - aplicativo para ser usado na linha de comando, vc pode
> usar essa classe no seu aplicativo swing sem problema, tem um m�todo
> statico onde vc passa o nome do arquivo e o endere�o do servidor.
> 
> recebeArquivo.java - este � uma servlet. ela � que salva o arquivo no drive
> c:\ vc pode alterar ela para um diretorio especifico ou melhor ainda, fazer
> com que ela leia isso de algum outro lugar para que fique customizavel
> (tipo ler um parametro do context que possa ser definido no web.xml)
> 
> Eu peguei o que ja tinha pronto e so mudei pra ser um pouco gen�rico.
> 
> []s Bulinha
> 
> PS.: tem tempo que eu fiz isso e foi as pressas ent�o tem coisa que n�o
> est� t�o bonita (tipo o nome da classe ta come�ando com min�sculo).
> 
> (See attached file: enviaArquivoHttp.zip)
> 
> 
> 
> 
> 
>                                                            
>                                           
>                                      
>                       Frederico Werly Julio                        
>                                           
>                              
>                       da Silva                      Para:   
> [EMAIL PROTECTED], "JugPetropolis (E-mail)"                    
>           
>                       <[EMAIL PROTECTED]        
> <[email protected]>                            
>                            
>                       sus.gov.br>                   cc:      (cco: RSZ012
> Desenvolvimento/Rio/Vale)                                  
>       
>                                                    
> Assunto: [JUG-Petro] RES: [riojug] Enviando Arquivos com Aplica��o Swing    
>            
>                       03/23/2005 06:06 PM                           
>                                           
>                             
>                       Responder a                            
>                                           
>                                    
>                       jug-petropolis                       
>                                                    
>                             
>                                                            
>                                           
>                                      
> 
> 
> 
> T� a� ... � uma boa id�ia tb , um outro colega deu a id�ia de fazer um
> upload ... vou dar uma estudada tb por essa linha ...
> 
> Gente , gostaria de agradecer a ajuda dos colegas ... j� tenho bastante
> id�ias agora para a aplica��o . OBRIGADO !
> 
> Abra�os,
> Fred.
>       -----Mensagem original-----
>       De: Daniel Gazineu [mailto:[EMAIL PROTECTED]
>       Enviada em: quarta-feira, 23 de mar�o de 2005 17:57
>       Para: [EMAIL PROTECTED]
>       Assunto: Re: [riojug] Enviando Arquivos com Aplica��o Swing
> 
>       Forma mais simples, talvez n�o a mais elegante:
> 
>       Faz um Servlet que fique esperando a requisi��o dos clientes. O
>       cliente faz uma requisi��o HTTP enviando o arquivo serializado no
>       corpo da requisi��o, o server, que conhece o que est� recebendo
>       retorna esse array de bytes pra objeto e faz o que quiser com ele.
> 
>       � isso que tu precisa?
> 
>       []�s
> 
>       Daniel Gazineu
>        ----- Original Message -----
>        From: Frederico Werly Julio da Silva
>        To: [EMAIL PROTECTED] ; JugPetropolis (E-mail)
>        Sent: Wednesday, March 23, 2005 5:36 PM
>        Subject: RES: [riojug] Enviando Arquivos com Aplica��o Swing
> 
> 
>         Assim , eu tenho um Arquivo XXX.zip em um munic�pio e preciso que
>        ele envie (transmita) esse arquivo aqui para um servidor dentro do
>        Datasus ... O tamanho do arquivo � +- 100k  , mais n�o posso usar
>        portas altas que precisem ser configuradas nos firewalls dos
>        munic�pios , pois ficaria muito dif�cil de dar suporte para eles...
>        s�o 5558 munic�pios .... eee mund�o s� ...
> 
>        pretendo usar swing pra fazer a aplica��o ... o que faltam � id�ias
>        de com fazer a transmiss�o .
> 
>         Abra�os e Muito Obrigado !!!!...
>         Fred.
> 
> 
> 
> 
>              -----Mensagem original-----
>              De: Cesar Mattos [mailto:[EMAIL PROTECTED]
>              Enviada em: quarta-feira, 23 de mar�o de 2005 16:53
>              Para: [EMAIL PROTECTED]
>              Assunto: RE: [riojug] Enviando Arquivos com Aplica��o Swing
> 
>              Como transmitem?
> 
>              O cliente se conecta ao programa?
> 
>              Ou o programa se conecta a outro servidor e envia o arquivo?
> 
>              Descreve melhor a�
> 
>              []'s
> 
>              FearL0rd
> 
> 
>              -----Original Message-----
>              From: Frederico Werly Julio da Silva
>              [mailto:[EMAIL PROTECTED]
>              Sent: Wednesday, March 23, 2005 3:19 PM
>              To: Rio-Jug (E-mail); JugPetropolis (E-mail)
>              Subject: [riojug] Enviando Arquivos com Aplica��o Swing
> 
> 
> 
> 
>                 Boa tarde pessoal ,
> 
>                   Eu tenho aqui na empresa um programa feito em Delphi que
>              transmite
>              arquivos aqui do sistema via HTTP , mais preciso agora
>              desenvolver um em
>              Java(Swing) para transmitir esses dados , oque voc�s sugerem ?
> 
>                   O Ideal � que fosse pela porta 80 por que esse programa
>              ser� baixado
>              por estados e munic�pios e ficaria dif�cil dar suporte a qual
>              porta abrir no
>              firewall de mais de 5000 munic�pios .
> 
>                   Ajudem a� ,
> 
>                   Abra�os,
>                   Fred.
> 
> 
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>              Rio Java Users Group    www.riojug.org
>              E-mail dos Moderadores  [EMAIL PROTECTED]
> 
>              Patroc�nio: Quality Software, SENAC-Rio CIT, Locaweb
>              Apoio: Java Magazine, SQL Magazine
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>              Participe tamb�m das outras listas do RioJUG:
>              SCJP (groups.yahoo.com/group/scjp_riojug)
>              SCWCD (groups.yahoo.com/group/scwcd_riojug)
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>              Yahoo! Groups Links
> 
> 
> 
> 
> 
> 
> 
> 
> 
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>              Rio Java Users Group    www.riojug.org
>              E-mail dos Moderadores  [EMAIL PROTECTED]
> 
>              Patroc�nio: Quality Software, SENAC-Rio CIT, Locaweb
>              Apoio: Java Magazine, SQL Magazine
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>              Participe tamb�m das outras listas do RioJUG:
>              SCJP (groups.yahoo.com/group/scjp_riojug)
>              SCWCD (groups.yahoo.com/group/scwcd_riojug)
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> 
> 
> 
> 
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>              Rio Java Users Group    www.riojug.org
>              E-mail dos Moderadores  [EMAIL PROTECTED]
> 
>              Patroc�nio: Quality Software, SENAC-Rio CIT, Locaweb
>              Apoio: Java Magazine, SQL Magazine
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>              Participe tamb�m das outras listas do RioJUG:
>              SCJP (groups.yahoo.com/group/scjp_riojug)
>              SCWCD (groups.yahoo.com/group/scwcd_riojug)
>             
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> 
> 
> 
> 
>      
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>       Rio Java Users Group    www.riojug.org
>       E-mail dos Moderadores  [EMAIL PROTECTED]
> 
>       Patroc�nio: Quality Software, SENAC-Rio CIT, Locaweb
>       Apoio: Java Magazine, SQL Magazine
>      
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
>       Participe tamb�m das outras listas do RioJUG:
>       SCJP (groups.yahoo.com/group/scjp_riojug)
>       SCWCD (groups.yahoo.com/group/scwcd_riojug)
>      
> -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> 
> 
>    
> Y 
> a 
> h 
> o 
> o 
> ! 
> G 
> r 
> o 
> u 
> p 
> s 
> S 
> p 
> o 
> n 
> s 
> o 
> r 
>    
>    
>    
> A 
> D 
> V 
> E 
> R 
> T 
> I 
> S 
> E 
> M 
> E 
> N 
> T 
>    
>    
>    
>    
>    
> 
> 
> 
>       Yahoo! Groups Links
>             To visit your group on the web, go to:
>             http://groups.yahoo.com/group/jug-petropolis/
> 
>             To unsubscribe from this group, send an email to:
>             [EMAIL PROTECTED]
> 
>             Your use of Yahoo! Groups is subject to the Yahoo! Terms of
>             Service.
> 
> 
>  
>  Yahoo! Groups Sponsor 
>  
>  ADVERTISEMENT
>  
>  ________________________________
>  Yahoo! Groups Links
>  
>  
> To visit your group on the web, go to:
> http://groups.yahoo.com/group/jug-petropolis/
>   
> To unsubscribe from this group, send an email to:
> [EMAIL PROTECTED]
>   
> Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service. 
>  
>


 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/jug-petropolis/

<*> To unsubscribe from this group, send an email to:
    [EMAIL PROTECTED]

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 
package siops.snet.api;
import java.io.*;
import java.net.*;
import javax.swing.*;

public class SnetClient  {
    
    private String NomeArquivo;
    private JProgressBar barraProgresso;
    
    public void enviaArquivo(String server) throws MalformedURLException, IOException, ProtocolException {
        URL url = new URL(server);
        File fi = new File(NomeArquivo);
        String nome = fi.getName();
        URLConnection urlConn = url.openConnection();
        if(urlConn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection)urlConn;
            httpConn.setRequestMethod("POST");
        }
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setDefaultUseCaches(false);
        
        String NEWLINE = "\r\n";
        String PREFIX = "--";
        
        DataOutputStream out = null;
        
        String boundary = "--------------------" + Long.toString(System.currentTimeMillis(), 16);
        
        String contenttype = "multipart/form-data; boundary=" + boundary;
        
        urlConn.setRequestProperty("Accept", "*/*");
        urlConn.setRequestProperty("Content-Type", contenttype);
        
        urlConn.setRequestProperty("Connection", "Keep-Alive");
        urlConn.setRequestProperty("Cache-Control", "no-cache");
        
        out = new DataOutputStream(urlConn.getOutputStream());
        
        
        //Transformo o Arquivo em um Stream para ser enviado.
        FileInputStream fis = null;
        boolean fileExists = true;
        try {
            fis = new FileInputStream(fi);
        } catch (FileNotFoundException e) {
            fileExists = false;
        }
        //Inicia a Barra de Progresso.
        Integer posicao = 0;
        if (barraProgresso != null){
            barraProgresso.setMaximum(Long.valueOf(fi.length()/4096).intValue());
            barraProgresso.setValue(0);
            barraProgresso.setStringPainted(true);
        }
        //Escrevo o Header do meu POST.
        out.writeBytes(PREFIX);
        out.writeBytes(boundary);
        out.writeBytes(NEWLINE);
        out.writeBytes("Content-Disposition: form-data; name=\"arquivo\"; filename=\""+nome+"\"");
        out.writeBytes(NEWLINE);
        out.writeBytes("Content-Type: image/jpg");
        out.writeBytes(NEWLINE);
        out.writeBytes(NEWLINE);
        // Envio o arquivo em pacotes de 4k(4096 bytes) .
        if(fileExists) {
            byte[] buffer= new byte[4096];
            int bytes = 0;
            //Envio os dados em pacotes de 4k .
            while((bytes = fis.read(buffer)) != -1) {
                out.write(buffer, 0, bytes);
                //Incremento a barra de progresso.
                if (barraProgresso != null){
                    posicao++;
                    corrigeProgressao(posicao);
                }
            }
            fis.close();
        }
        
        out.writeBytes(NEWLINE);
        out.writeBytes(PREFIX);
        out.writeBytes(boundary);
        out.writeBytes(PREFIX);
        out.writeBytes(NEWLINE);
        out.flush();
        BufferedInputStream bi = new BufferedInputStream(urlConn.getInputStream());
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        int tmp =0;
        while ( (tmp = bi.read()) >-1 ){
            bo.write(tmp);
        }
        out.close();
        ((HttpURLConnection)urlConn).disconnect();
    }
    
    public JProgressBar getBarraProgresso() {
        return barraProgresso;
    }
    
    public void setBarraProgresso(JProgressBar barraProgresso) {
        this.barraProgresso = barraProgresso;
    }
    
    public String getNomeArquivo() {
        return NomeArquivo;
    }
    
    public void setNomeArquivo(String NomeArquivo) {
        this.NomeArquivo = NomeArquivo;
    }
    
    public void corrigeProgressao(int valor) {
        this.barraProgresso.setValue(valor);
        this.barraProgresso.setIndeterminate(false);
        this.barraProgresso.setStringPainted(true);
        this.barraProgresso.setBorderPainted(true);
        this.barraProgresso.repaint();
    }
    
}
/*
 * frmPrincipal.java
 *
 * Created on 6 de Maio de 2005, 17:42
 */

package siops.snet.form;
import siops.snet.api.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import java.net.*;
import javax.swing.*;
import javax.swing.filechooser.*;


/**
 *
 * @author  Frederico.werly
 */
public class frmPrincipal extends javax.swing.JFrame {
    JFrame frame;
    /** Creates new form frmPrincipal */
    public frmPrincipal() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        btnTransmite = new javax.swing.JButton();
        edtPath = new javax.swing.JTextField();
        btnProcurar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        pgbProgresso = new javax.swing.JProgressBar();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        getContentPane().setLayout(null);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("<<< SIOPS NET >>> Prot\u00f3tipo");
        setResizable(false);
        btnTransmite.setIcon(new javax.swing.ImageIcon("C:\\Fred\\Java\\Swing\\Snet_Client\\src\\resources\\trans.gif"));
        btnTransmite.setText("Transmitir");
        btnTransmite.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTransmiteActionPerformed(evt);
            }
        });

        getContentPane().add(btnTransmite);
        btnTransmite.setBounds(60, 150, 120, 25);

        edtPath.setName("edtPath");
        getContentPane().add(edtPath);
        edtPath.setBounds(50, 60, 200, 20);

        btnProcurar.setText("...");
        btnProcurar.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(255, 0, 255), java.awt.Color.red, new java.awt.Color(255, 255, 0), java.awt.Color.green));
        btnProcurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProcurarActionPerformed(evt);
            }
        });

        getContentPane().add(btnProcurar);
        btnProcurar.setBounds(250, 60, 30, 20);

        btnSair.setIcon(new javax.swing.ImageIcon("C:\\Fred\\Java\\Swing\\Snet_Client\\src\\resources\\sair.gif"));
        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        getContentPane().add(btnSair);
        btnSair.setBounds(190, 150, 80, 23);

        jLabel1.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel1.setText("*Selecione um arquivo e clique em transmitir ");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(30, 10, 300, 20);

        getContentPane().add(pgbProgresso);
        pgbProgresso.setBounds(50, 110, 230, 18);

        jLabel2.setText("Status da Transmiss\u00e3o");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(100, 90, 130, 14);

        jLabel3.setText("Arquivo :");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(130, 40, 110, 14);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-335)/2, (screenSize.height-229)/2, 335, 229);
    }
    // </editor-fold>//GEN-END:initComponents
    
    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnSairActionPerformed
    
    private void btnProcurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProcurarActionPerformed
        JFileChooser fc;
        fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(frmPrincipal.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            edtPath.setText(file.getPath());
        }
    }//GEN-LAST:event_btnProcurarActionPerformed
    
    private void btnTransmiteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTransmiteActionPerformed
        //Envio os dados dentro de uma nova Thread, para que n�o congele minha 
        //tela enquanto transmite o arquivo.
        Thread t = new Thread() {
            public void run() {
                SnetClient transmissor = new SnetClient();
                transmissor.setNomeArquivo(edtPath.getText());
                transmissor.setBarraProgresso(pgbProgresso);
                try {
                    transmissor.enviaArquivo("http://sede-1385.datasus.gov:8084/SIOPS/Snet_Serv";); //"http://sede-1385.datasus.gov:8084/SIOPS/Snet_Serv";
                    JOptionPane.showMessageDialog(frame,"Seu Arquivo foi Transmitido com Sucesso .",
                    "<< SIOPS NET >>",JOptionPane.INFORMATION_MESSAGE);
                }catch(Exception e){
                    JOptionPane.showMessageDialog(frame,"Erro : Seu Arquivo n�o foi Transmitido .",
                            "<< SIOPS NET >>",JOptionPane.ERROR_MESSAGE);
                    e.printStackTrace();
                }
            }
            
        };
        t.start();                  
    }//GEN-LAST:event_btnTransmiteActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch(Exception e) {
            System.out.println("Error setting Java LAF: " + e);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmPrincipal().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnProcurar;
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnTransmite;
    private javax.swing.JTextField edtPath;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JProgressBar pgbProgresso;
    // End of variables declaration//GEN-END:variables
    
}
package snet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;



public class Snet_Serv extends HttpServlet  {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
    
    
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String NEWLINE = "\r\n";
        BufferedInputStream bi = new BufferedInputStream( request.getInputStream());
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        int tmp=0;
        while (  ( tmp =     bi.read()) > -1)
            bo.write(tmp);
        String content = bo.toString();
        String boundary = content.substring(0, content.indexOf(NEWLINE));
        int inicioNome = content.indexOf("filename=\"") + 10 ;
        String nome = content.substring(inicioNome  , content.indexOf( "\"",inicioNome + 1));
        int inicioArq = content.indexOf(NEWLINE + NEWLINE) + 4;
        int fimArq = content.indexOf(boundary, inicioArq )-2;
        
        
        FileOutputStream fo = new FileOutputStream(new File("c:\\Downloads\\" + nome));
        fo.write(bo.toByteArray(), inicioArq, fimArq - inicioArq);
        fo.close();
    }
    
}

Atrašyti