Guest User

Untitled

a guest
Jul 22nd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. HttpPost httppost = new HttpPost("some path");
  2. HttpClient httpclient = new DefaultHttpClient();
  3. try {
  4. File file = new File("file path");
  5. InputStream in = new BufferedInputStream(new FileInputStream(file));
  6. byte[] bArray = new byte[(int) file.length()];
  7. in.read(bArray);
  8. String entity = Base64.encodeToString(bArray, Base64.DEFAULT);
  9. httppost.setEntity(new StringEntity(entity));
  10. HttpResponse response = httpclient.execute(httppost);
  11. }
  12.  
  13. private class FileUploadTask extends AsyncTask<Object, Integer, Void> {
  14.  
  15. private ProgressDialog dialog;
  16.  
  17. @Override
  18. protected void onPreExecute() {
  19. dialog = new ProgressDialog(TheActivity.this);
  20. dialog.setMessage("Uploading...");
  21. dialog.setIndeterminate(false);
  22. dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  23. dialog.setProgress(0);
  24. dialog.show();
  25. }
  26.  
  27. @Override
  28. protected Void doInBackground(Object... arg0) {
  29. try {
  30. File file = new File("file path");
  31. FileInputStream fileInputStream = new FileInputStream(file);
  32. byte[] bytes = new byte[(int) file.length()];
  33. fileInputStream.read(bytes);
  34. fileInputStream.close();
  35.  
  36. URL url = new URL("some path");
  37. HttpURLConnection connection =
  38. (HttpURLConnection) url.openConnection();
  39. OutputStream outputStream = connection.getOutputStream();
  40.  
  41. int bufferLength = 1024;
  42. for (int i = 0; i < bytes.length; i += bufferLength) {
  43. int progress = (int)((i / (float) bytes.length) * 100);
  44. publishProgress(progress);
  45. if (bytes.length - i >= bufferLength) {
  46. outputStream.write(bytes, i, bufferLength);
  47. } else {
  48. outputStream.write(bytes, i, bytes.length - i);
  49. }
  50. }
  51. publishProgress(100);
  52.  
  53. outputStream.close();
  54. outputStream.flush();
  55.  
  56. InputStream inputStream = connection.getInputStream();
  57. // read the response
  58. inputStream.close();
  59.  
  60. } catch (MalformedURLException e) {
  61. e.printStackTrace();
  62. } catch (IOException e) {
  63. e.printStackTrace();
  64. }
  65. return null;
  66. }
  67.  
  68. @Override
  69. protected void onProgressUpdate(Integer... progress) {
  70. dialog.setProgress(progress[0]);
  71. }
  72.  
  73. @Override
  74. protected void onPostExecute(Void result) {
  75. try {
  76. dialog.dismiss();
  77. } catch(Exception e) {
  78. }
  79.  
  80. }
  81.  
  82. }
Add Comment
Please, Sign In to add comment