Advertisement
Guest User

Untitled

a guest
May 27th, 2012
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | None | 0 0
  1. URLConnection urlConnection = new URL("http://meineSeite.de/upload.php").openConnection();
  2.  
  3. ((HttpURLConnection) urlConnection).setRequestMethod("POST");
  4. String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
  5. String CRLF = "\r\n"; // Line separator required by multipart/form-data.
  6.  
  7. urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
  8. urlConnection.setDoOutput(true);
  9. urlConnection.setDoInput(true);
  10. urlConnection.setUseCaches(false);
  11. urlConnection.setDefaultUseCaches(false);
  12. OutputStream os = urlConnection.getOutputStream();
  13.  
  14. PrintWriter writer = new PrintWriter(os);
  15.  
  16. writer.append("--" + boundary).append(CRLF);
  17. if (postRequest.get(requestKey) instanceof File) {
  18.     File requestValue = (File) postRequest.get(requestKey);
  19.     writer.append("Content-Disposition: form-data; name=\""
  20.             + requestKey + "\"; filename=\""
  21.             + requestValue.getName() + "\"").append(CRLF);
  22.     writer.append("Content-Type: "
  23.             + URLConnection.guessContentTypeFromName(requestValue.getName())).append(CRLF);
  24.     writer.append(CRLF).flush();
  25.     InputStream input = null;
  26.     try {
  27.         final long totalLenght = requestValue.length();
  28.         long lenghtUploaded = 0L;
  29.         input = new FileInputStream(requestValue);
  30.         byte lastPercentage = -1;
  31.         byte[] buffer = new byte[100];
  32.         for (int length = 0; (length = input.read(buffer)) > 0;) {
  33.             os.write(buffer, 0, length);
  34.             lenghtUploaded = lenghtUploaded + length;
  35.             byte percentage = (byte) (lenghtUploaded / (totalLenght / 100));                       
  36.             if ((percentage != lastPercentage) && (uploadObserver != null))
  37.                 uploadObserver.onPercentageChange(lastPercentage, percentage);
  38.            
  39.            
  40.             lastPercentage = percentage;
  41.             os.flush();
  42.             writer.flush();
  43.         }
  44.                            
  45.         os.flush();
  46.     } finally {
  47.         if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
  48.     }
  49.     writer.append(CRLF).flush(); // CRLF is important! It indicates end of binary boundary.
  50. }
  51.  
  52.  
  53. writer.append("--" + boundary + "--").append(CRLF).flush();
  54. os.close();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement