Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- URLConnection urlConnection = new URL("http://meineSeite.de/upload.php").openConnection();
- ((HttpURLConnection) urlConnection).setRequestMethod("POST");
- String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
- String CRLF = "\r\n"; // Line separator required by multipart/form-data.
- urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
- urlConnection.setDoOutput(true);
- urlConnection.setDoInput(true);
- urlConnection.setUseCaches(false);
- urlConnection.setDefaultUseCaches(false);
- OutputStream os = urlConnection.getOutputStream();
- PrintWriter writer = new PrintWriter(os);
- writer.append("--" + boundary).append(CRLF);
- if (postRequest.get(requestKey) instanceof File) {
- File requestValue = (File) postRequest.get(requestKey);
- writer.append("Content-Disposition: form-data; name=\""
- + requestKey + "\"; filename=\""
- + requestValue.getName() + "\"").append(CRLF);
- writer.append("Content-Type: "
- + URLConnection.guessContentTypeFromName(requestValue.getName())).append(CRLF);
- writer.append(CRLF).flush();
- InputStream input = null;
- try {
- final long totalLenght = requestValue.length();
- long lenghtUploaded = 0L;
- input = new FileInputStream(requestValue);
- byte lastPercentage = -1;
- byte[] buffer = new byte[100];
- for (int length = 0; (length = input.read(buffer)) > 0;) {
- os.write(buffer, 0, length);
- lenghtUploaded = lenghtUploaded + length;
- byte percentage = (byte) (lenghtUploaded / (totalLenght / 100));
- if ((percentage != lastPercentage) && (uploadObserver != null))
- uploadObserver.onPercentageChange(lastPercentage, percentage);
- lastPercentage = percentage;
- os.flush();
- writer.flush();
- }
- os.flush();
- } finally {
- if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
- }
- writer.append(CRLF).flush(); // CRLF is important! It indicates end of binary boundary.
- }
- writer.append("--" + boundary + "--").append(CRLF).flush();
- os.close();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement