Enviar arquivos!

8 respostas
rafaelt

Fala ae galerinha boa…

Gostaria de saber como faco para enviar arquivos para um servidor web (apache) atraves do JAVA, criei uma interface que abre o arquivo de um disco local, agora gostaria de saber como faco para enviar esse arquivo para uma determinada pasta no servidor web…

Abs,
Rafael

8 Respostas

luuu

usa essa api que voce consegue

http://jakarta.apache.org/commons/fileupload/

KWill

Esse apache que você está usando, é o Apache2 ou é o Apache Tomcat? Os 2 web servers são bem diferentes…

Se você estiver usando Tomcat, tem a library FileUpload dentro do projeto Apache.Jakarta:

http://jakarta.apache.org/commons/fileupload/

Baixa aí e veja se ajuda, tem uma documentação boa na página do projeto.

Espero ter ajudado

Inté

T

Procure por WebDAV.
Você terá de habilitar esse recurso no Apache, e achar um cliente WebDAV em Java.
Normalmente os editores Web (como o FrontPage ou o DreamWeaver) são clientes WebDAV, então você poderá testar se isso funciona.

rafaelt

Fala galera, eh o Apache (do PHP), tipo to usando socket, e essa interface logo logo vou implementa-la para ser um applet.

pretendo fazer um applet para o cara abrir um arquivo e enviar numa pasta do servidor web.

alguma sugest~ao simples???

rafaelt

Galera aqui vai a source do meu programa.
Lembrando nao estou usando servlet.

Quem puder me ajudar.

import java.io.*;
import java.io.FileInputStream.*;
import java.io.DataInputStream.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.net.*;

public class upMenu extends JPanel implements ActionListener
{
	//////////-----TESTE-----\\\\\
	//Connections.
	String serverName = "localhost";
    int serverPort = 80;
    String fileUploadPath = "/upload";
    String scriptPath = "/upload/getupload.php";
    
    InetAddress addr;
    Socket socket;
    BufferedOutputStream wr;
    
    Thread m_thread;
    int uploadPacketSize = 80 * 1024;
    //////////-----TESTE-----\\\\\
   
	static private final String newline = "\n";
	JButton openButton, /*sendButton,*/ cancelButton; //Abrir, enviar e cancelar.
	JTextArea log;
	JFileChooser fc;
	
	public upMenu()
	{
		super(new BorderLayout());
		
		//Parte de info aqui.
		log = new JTextArea(15, 40);
		log.setMargin(new Insets(5, 5, 5, 5));
		log.setEditable(false);
		JScrollPane logScrollPane = new JScrollPane(log);
		
		fc = new JFileChooser();
		
		//Abrir
		openButton = new JButton("Abrir"); //Implementar imagem.
		openButton.addActionListener(this);
		
		//Enviar
		//sendButton = new JButton("Enviar");
		//sendButton.addActionListener(this);
		
		//-----Cancelar
		cancelButton = new JButton("Cancelar");
		cancelButton.addActionListener(this);
		//-----Cancelar
		
		//Painel
		JPanel buttonPanel = new JPanel();
		buttonPanel.add(openButton);
		//buttonPanel.add(sendButton);
		buttonPanel.add(cancelButton);
		
		//Adicionando os recursos no painel.
		add(buttonPanel, BorderLayout.PAGE_START);
		add(logScrollPane, BorderLayout.CENTER);
	}
	
	public void actionPerformed(ActionEvent e)
	{
		//Acão nos botões.
		if(e.getSource() == openButton)
		{
			int returnVal = fc.showOpenDialog(upMenu.this);
			
			if(returnVal == JFileChooser.APPROVE_OPTION)
			{
				File file = fc.getSelectedFile();
				long fileSize = file.length(); //Tamanho do arquivo.
				//FileReader in = null;

				try
				{
					log.append("Inicializando " +serverName+ "..." + newline);
					addr = InetAddress.getByName(serverName);
					log.append("Conectando com "+serverName+" na porta "+serverPort+"..." + newline);
					socket = new Socket(addr, serverPort);
					log.append("Conectado, criando saída em: "+fileUploadPath+"" + newline);
					//log.append("Enviando: " + file.getName() + " Tamanho: " + fileSize + newline + newline);
				}
				
				catch(Exception e1)
        		{
            		log.append("Erro ao se conectar com o host: " + e1.getMessage());
            		log.invalidate();
            		return;
        		}
        		
        		/*****
        		try
        		{
        			wr = new BufferedOutputStream(socket.getOutputStream());
        		}
        		
        		catch(Exception e2)
        		{
            		log.append("Não foi possível enviar o arquivo para: "  + e2.getMessage());
            		log.invalidate();
            		return;
        		}
        		*****/
        		
        		//Preparando o que vai ser enviado.
        		//long contentLength;
        		//String fileHeader = "Content-Disposition", "attachment; Arquivo=" + file.getName() + "Content-type: application/octet-stream\r\n\r\n"; //Null???
			}
			
			else
			{
				log.append("Usuário desistiu de enviar o arquivo." + newline);
			}
			
			log.setCaretPosition(log.getDocument().getLength());
		}
		
		else if(e.getSource() == cancelButton)
		{
			int returnVal = fc.showSaveDialog(upMenu.this); //Mudar
				
			if(returnVal == JFileChooser.APPROVE_OPTION)
			{
				File file = fc.getSelectedFile();
				log.append("");
			}
			
			else
			{
				log.append("");
			}
			
			log.setCaretPosition(log.getDocument().getLength());
		}
	}
	
	private static void createAndShowGUI()
	{
		JFrame frame = new JFrame("Upload de 10 arquivos");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JComponent newContentPane = new upMenu();
		newContentPane.setOpaque(true);
		frame.setContentPane(newContentPane);
				
		//Mostrando a janela.
		frame.pack();
		frame.setVisible(true);
	}
			
	public static void main(String[] args)
	{
		javax.swing.SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				createAndShowGUI();
			}
		});
	}
}

Valeu ai!!!

rafaelt

Alguem poderia me ajudar a enviar um arquivo para um servidor web com o codigo acima???

Abs,
Rafael.

rafaelt

thingol:
Procure por WebDAV.
Você terá de habilitar esse recurso no Apache, e achar um cliente WebDAV em Java.
Normalmente os editores Web (como o FrontPage ou o DreamWeaver) são clientes WebDAV, então você poderá testar se isso funciona.

Baixei esse tal de WebDAV, mas nao entendi nada nele…pode me explicar???

Valeu
Rafael

lreao

Olá amigo, estou com um problema parecido!!
No meu caso, eu crio um aruivo html via java e via aaplet eu redireciono para o arquivo criado. funciona perfeitamente local, porém não consigo gravar o arquivo no servidor e é isso que preciso!!

Se teve uma solução, poderia postar?? Aí adapto para o meu caso!

Abraço

Criado 26 de outubro de 2006
Ultima resposta 13 de jun. de 2013
Respostas 8
Participantes 5