Advertisement
Guest User

How to get a progress bar for a file upload with Apache HttpClient 4

a guest
Apr 4th, 2012
1,861
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.66 KB | None | 0 0
  1. public static void main(String[] args) throws Exception
  2. {
  3. String fileName = "test.avi";
  4. File file = new File(fileName);
  5.  
  6. String serverResponse = null;
  7. HttpParams params = new BasicHttpParams();
  8. params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
  9. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  10. HttpClient client = new DefaultHttpClient(params);
  11. HttpPut put = new HttpPut("http://localhost:8080/" + fileName);
  12.  
  13. FileEntity fileEntity = new FileEntity(file, "binary/octet-stream");
  14. put.setEntity(fileEntity);
  15.  
  16. HttpResponse response = client.execute(put);
  17. HttpEntity entity = response.getEntity();
  18. if (entity != null)
  19. {
  20. serverResponse = EntityUtils.toString(entity);
  21. System.out.println(serverResponse);
  22. }
  23. }
  24.  
  25. import java.awt.event.ActionEvent;
  26. import java.awt.event.ActionListener;
  27. import java.io.File;
  28. import java.util.logging.Level;
  29. import java.util.logging.Logger;
  30. import javax.swing.JButton;
  31. import javax.swing.JFrame;
  32. import javax.swing.JPanel;
  33. import javax.swing.JProgressBar;
  34. import org.apache.http.HttpEntity;
  35. import org.apache.http.HttpResponse;
  36. import org.apache.http.HttpVersion;
  37. import org.apache.http.client.HttpClient;
  38. import org.apache.http.client.methods.HttpPut;
  39. import org.apache.http.impl.client.DefaultHttpClient;
  40. import org.apache.http.params.BasicHttpParams;
  41. import org.apache.http.params.HttpParams;
  42. import org.apache.http.params.HttpProtocolParams;
  43. import org.apache.http.util.EntityUtils;
  44.  
  45. public class ApplicationView implements ActionListener
  46. {
  47.  
  48. File file = new File("C:/Temp/my-upload.avi");
  49. JProgressBar progressBar = null;
  50.  
  51. public ApplicationView()
  52. {
  53. super();
  54. }
  55.  
  56. public void createView()
  57. {
  58. JFrame frame = new JFrame("File Upload with progress bar - Example");
  59. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  60. frame.setBounds(0, 0, 300, 200);
  61. frame.setVisible(true);
  62.  
  63. progressBar = new JProgressBar(0, 100);
  64. progressBar.setBounds(20, 20, 200, 30);
  65. progressBar.setStringPainted(true);
  66. progressBar.setVisible(true);
  67.  
  68. JButton button = new JButton("upload");
  69. button.setBounds(progressBar.getX(),
  70. progressBar.getY() + progressBar.getHeight() + 20,
  71. 100,
  72. 40);
  73. button.addActionListener(this);
  74.  
  75. JPanel panel = (JPanel) frame.getContentPane();
  76. panel.setLayout(null);
  77. panel.add(progressBar);
  78. panel.add(button);
  79. panel.setVisible(true);
  80. }
  81.  
  82. public void actionPerformed(ActionEvent e)
  83. {
  84. try
  85. {
  86. sendFile(this.file, this.progressBar);
  87. }
  88. catch (Exception ex)
  89. {
  90. System.out.println(ex.getLocalizedMessage());
  91. }
  92. }
  93.  
  94. private void sendFile(File file, JProgressBar progressBar) throws Exception
  95. {
  96. String serverResponse = null;
  97. HttpParams params = new BasicHttpParams();
  98. params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
  99. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  100. HttpClient client = new DefaultHttpClient(params);
  101. HttpPut put = new HttpPut("http://localhost:8080/" + file.getName());
  102.  
  103. ProgressBarListener listener = new ProgressBarListener(progressBar);
  104. FileEntityWithProgressBar fileEntity = new FileEntityWithProgressBar(file, "binary/octet-stream", listener);
  105. put.setEntity(fileEntity);
  106.  
  107. HttpResponse response = client.execute(put);
  108. HttpEntity entity = response.getEntity();
  109. if (entity != null)
  110. {
  111. serverResponse = EntityUtils.toString(entity);
  112. System.out.println(serverResponse);
  113. }
  114. }
  115. }
  116.  
  117. import java.io.File;
  118. import java.io.FileInputStream;
  119. import java.io.IOException;
  120. import java.io.InputStream;
  121. import java.io.OutputStream;
  122. import org.apache.http.entity.AbstractHttpEntity;
  123.  
  124. /**
  125. * File entity which supports a progress bar.<br/>
  126. * Based on "org.apache.http.entity.FileEntity".
  127. * @author Benny Neugebauer (www.bennyn.de)
  128. */
  129. public class FileEntityWithProgressBar extends AbstractHttpEntity implements Cloneable
  130. {
  131.  
  132. protected final File file;
  133. private final ProgressBarListener listener;
  134. private long transferredBytes;
  135.  
  136. public FileEntityWithProgressBar(final File file, final String contentType, ProgressBarListener listener)
  137. {
  138. super();
  139. if (file == null)
  140. {
  141. throw new IllegalArgumentException("File may not be null");
  142. }
  143. this.file = file;
  144. this.listener = listener;
  145. this.transferredBytes = 0;
  146. setContentType(contentType);
  147. }
  148.  
  149. public boolean isRepeatable()
  150. {
  151. return true;
  152. }
  153.  
  154. public long getContentLength()
  155. {
  156. return this.file.length();
  157. }
  158.  
  159. public InputStream getContent() throws IOException
  160. {
  161. return new FileInputStream(this.file);
  162. }
  163.  
  164. public void writeTo(final OutputStream outstream) throws IOException
  165. {
  166. if (outstream == null)
  167. {
  168. throw new IllegalArgumentException("Output stream may not be null");
  169. }
  170. InputStream instream = new FileInputStream(this.file);
  171. try
  172. {
  173. byte[] tmp = new byte[4096];
  174. int l;
  175. while ((l = instream.read(tmp)) != -1)
  176. {
  177. outstream.write(tmp, 0, l);
  178. this.transferredBytes += l;
  179. this.listener.updateTransferred(this.transferredBytes);
  180. }
  181. outstream.flush();
  182. }
  183. finally
  184. {
  185. instream.close();
  186. }
  187. }
  188.  
  189. public boolean isStreaming()
  190. {
  191. return false;
  192. }
  193.  
  194. @Override
  195. public Object clone() throws CloneNotSupportedException
  196. {
  197. return super.clone();
  198. }
  199. }
  200.  
  201. import javax.swing.JProgressBar;
  202.  
  203. public class ProgressBarListener
  204. {
  205.  
  206. private int transferedMegaBytes = 0;
  207. private JProgressBar progressBar = null;
  208.  
  209. public ProgressBarListener()
  210. {
  211. super();
  212. }
  213.  
  214. public ProgressBarListener(JProgressBar progressBar)
  215. {
  216. this();
  217. this.progressBar = progressBar;
  218. }
  219.  
  220. public void updateTransferred(long transferedBytes)
  221. {
  222. transferedMegaBytes = (int) (transferedBytes / 1048576);
  223. this.progressBar.setValue(transferedMegaBytes);
  224. this.progressBar.paint(progressBar.getGraphics());
  225. System.out.println("Transferred: " + transferedMegaBytes + " Megabytes.");
  226. }
  227. }
  228.  
  229. public class FileEntity extends org.apache.http.entity.FileEntity {
  230.  
  231. private OutputStreamProgress outstream;
  232.  
  233. public FileEntity(File file, String contentType) {
  234. super(file, contentType);
  235. }
  236.  
  237. @Override
  238. public void writeTo(OutputStream outstream) throws IOException {
  239. this.outstream = new OutputStreamProgress(outstream);
  240. super.writeTo(this.outstream);
  241. }
  242.  
  243. /**
  244. * Progress: 0-100
  245. */
  246. public int getProgress() {
  247. if (outstream == null) {
  248. return 0;
  249. }
  250. long contentLength = getContentLength();
  251. if (contentLength <= 0) { // Prevent division by zero and negative values
  252. return 0;
  253. }
  254. long writtenLength = outstream.getWrittenLength();
  255. return (int) (100*writtenLength/contentLength);
  256. }
  257. }
  258.  
  259. public class OutputStreamProgress extends OutputStream {
  260.  
  261. private final OutputStream outstream;
  262. private volatile long bytesWritten=0;
  263.  
  264. public OutputStreamProgress(OutputStream outstream) {
  265. this.outstream = outstream;
  266. }
  267.  
  268. @Override
  269. public void write(int b) throws IOException {
  270. outstream.write(b);
  271. bytesWritten++;
  272. }
  273.  
  274. @Override
  275. public void write(byte[] b) throws IOException {
  276. outstream.write(b);
  277. bytesWritten += b.length;
  278. }
  279.  
  280. @Override
  281. public void write(byte[] b, int off, int len) throws IOException {
  282. outstream.write(b, off, len);
  283. bytesWritten += len;
  284. }
  285.  
  286. @Override
  287. public void flush() throws IOException {
  288. outstream.flush();
  289. }
  290.  
  291. @Override
  292. public void close() throws IOException {
  293. outstream.close();
  294. }
  295.  
  296. public long getWrittenLength() {
  297. return bytesWritten;
  298. }
  299. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement