반응형
swing 으로 제작되었으며 아파치의 HttpClient 를 이용한 웹서비스에 파일 업로드하기 |
개발환경 : JDK 1.5, eclipse-galileo, window XP, HttpClient 3.1 |
여기에 소개된 java application은 swing 으로 제작되었으며 일반 main 이 들어간
예제보다는 보다 직관적으로 테스트가 가능하고 애플릿에도 활용하면 좋을 것 같다.
이 프로그램에서 쓰인 HttpClient 는 org.apache.commons.httpclient.HttpClient 클래스이며
commons-httpclient-3.1.jar 에 포함되어있다. 다운로드는 아파치 사이트에서 받으면
되는데 주소는 다음과 같다. http://hc.apache.org/downloads.cgi
상단에 있는 HttpClient 4.0.1 은 다른것이며 아래 쪽으로 내려가서 Commons HttpClient 3.1
을 받도록 한다. 받은 jar 는 어플리케이션 라이브러리에 추가한다소스와 완성된 프로젝트를 올렸으니 참고하기 바란다.
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.params.HttpMethodParams; public class MultipartFileUploadApp { public static void main(String[] args) { MultipartFileUploadFrame f = new MultipartFileUploadFrame(); f.setTitle("HTTP multipart file upload application"); f.pack(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); f.setVisible(true); } public static class MultipartFileUploadFrame extends JFrame { private File targetFile; private JTextArea taTextResponse; private DefaultComboBoxModel cmbURLModel; public MultipartFileUploadFrame() { String[] aURLs = { "http://localhost:8080/httpclienttest/fileupload" }; cmbURLModel = new DefaultComboBoxModel(aURLs); final JComboBox cmbURL = new JComboBox(cmbURLModel); cmbURL.setToolTipText("Enter a URL"); cmbURL.setEditable(true); cmbURL.setSelectedIndex(0); JLabel lblTargetFile = new JLabel("Selected file:"); final JTextField tfdTargetFile = new JTextField(30); tfdTargetFile.setEditable(false); final JCheckBox cbxExpectHeader = new JCheckBox( "Use Expect header"); cbxExpectHeader.setSelected(false); final JButton btnDoUpload = new JButton("Upload"); btnDoUpload.setEnabled(false); final JButton btnSelectFile = new JButton("Select a file..."); btnSelectFile.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { JFileChooser chooser = new JFileChooser(); chooser.setFileHidingEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setMultiSelectionEnabled(false); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setDialogTitle("Choose a file..."); if ( chooser.showOpenDialog( MultipartFileUploadFrame.this) == JFileChooser.APPROVE_OPTION ) { targetFile = chooser.getSelectedFile(); tfdTargetFile.setText(targetFile.toString()); btnDoUpload.setEnabled(true); } } } ); taTextResponse = new JTextArea(10, 40); taTextResponse.setEditable(false); final JLabel lblURL = new JLabel("URL:"); btnDoUpload.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String targetURL = cmbURL.getSelectedItem().toString(); // add the URL to the combo model // if it's not already there if (!targetURL .equals( cmbURLModel.getElementAt( cmbURL.getSelectedIndex()))) { cmbURLModel.addElement(targetURL); } PostMethod filePost = new PostMethod(targetURL); filePost.getParams().setBooleanParameter( HttpMethodParams.USE_EXPECT_CONTINUE, cbxExpectHeader.isSelected()); try { appendMessage("Uploading " + targetFile.getName() + " to " + targetURL); Part[] parts = { new FilePart(targetFile.getName(), targetFile) }; filePost.setRequestEntity( new MultipartRequestEntity(parts, filePost.getParams()) ); HttpClient client = new HttpClient(); client.getHttpConnectionManager(). getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { appendMessage( "Upload complete, response=" + filePost.getResponseBodyAsString() ); } else { appendMessage( "Upload failed, response=" + HttpStatus.getStatusText(status) ); } } catch (Exception ex) { appendMessage("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.gridheight = 1; c.gridwidth = 1; c.gridx = 0; c.gridy = 0; c.insets = new Insets(10, 5, 5, 0); c.weightx = 1; c.weighty = 1; getContentPane().add(lblURL, c); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.HORIZONTAL; c.gridwidth = 2; c.gridx = 1; c.insets = new Insets(5, 5, 5, 10); getContentPane().add(cmbURL, c); c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.insets = new Insets(10, 5, 5, 0); c.gridwidth = 1; c.gridx = 0; c.gridy = 1; getContentPane().add(lblTargetFile, c); c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 5, 5, 5); c.gridwidth = 1; c.gridx = 1; getContentPane().add(tfdTargetFile, c); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; c.insets = new Insets(5, 5, 5, 10); c.gridwidth = 1; c.gridx = 2; getContentPane().add(btnSelectFile, c); c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.NONE; c.insets = new Insets(10, 10, 10, 10); c.gridwidth = 3; c.gridx = 0; c.gridy = 2; getContentPane().add(cbxExpectHeader, c); c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.NONE; c.insets = new Insets(10, 10, 10, 10); c.gridwidth = 3; c.gridx = 0; c.gridy = 3; getContentPane().add(btnDoUpload, c); c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(10, 10, 10, 10); c.gridwidth = 3; c.gridheight = 3; c.weighty = 3; c.gridx = 0; c.gridy = 4; getContentPane().add(new JScrollPane(taTextResponse), c); } private void appendMessage(String m) { taTextResponse.append(m + "\n"); } } }
반응형
'자바(JAVA)' 카테고리의 다른 글
input 박스에 자동 submit 막기를 위한 여러가지 방법 (6) | 2010.08.02 |
---|---|
SQL Statement Log 를 보기위한 log4jdbc 사용법 (1) | 2010.08.02 |
Controller 영역인 브라우저에서의 단위테스트를 위한 HtmlUnit 사용하기 (0) | 2010.08.02 |
Ajax 을 사용하여 Form 데이터를 POST 전송하고자 할 때 (4) | 2010.08.02 |
아파치에서 배포하는 HttpClient 3.x 를 이용해 네트워크 데이터 전송 (5) | 2010.07.30 |
JAVA 에서 데이터 교환을 위해 JSON 사용하기 (0) | 2010.07.20 |
google SMTP 를 이용해서 java 에서 Email 보내기 테스트 (1) | 2010.07.19 |
Spring 에서 트랜잭션 설정시 NoClassDefFoundError TransactionManager 에러 (0) | 2010.07.18 |