마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

Multipart 업로드시 실제 progressbar 표시

0 추천

Multipart Upload 시 progressbar 구현을 하고 있는데 다음 코드를 참조해서 구현중입니다.

class BackgroundUploader extends AsyncTask<Void, Integer, Void> implements DialogInterface.OnCancelListener {

  private ProgressDialog progressDialog;
  private String url;
  private File file;

   public BackgroundUploader(String url, File file) {
    this.url = url;
    this.file = file; 
  }

   @Override
  protected void onPreExecute() {
    progressDialog = new ProgressDialog(context);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setMessage("Uploading...");
    progressDialog.setCancelable(false);
    progressDialog.setMax((int) file.length());
    progressDialog.show();
  }

   @Override
  protected Void doInBackground(Void... v) {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection connection = null;
    String fileName = file.getName();
    try {
      connection = (HttpURLConnection) new URL(url).openConnection();
      connection.setRequestMethod("POST");
      String boundary = "---------------------------boundary";
      String tail = "\r\n--" + boundary + "--\r\n";
      connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
      connection.setDoOutput(true);

      String metadataPart = "--" + boundary + "\r\n" 
          + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
          + "" + "\r\n";

      String fileHeader1 = "--" + boundary + "\r\n"
          + "Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
          + fileName + "\"\r\n"
          + "Content-Type: application/octet-stream\r\n"
          + "Content-Transfer-Encoding: binary\r\n";

       long fileLength = file.length() + tail.length();
      String fileHeader2 = "Content-length: " + fileLength + "\r\n";
      String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
      String stringData = metadataPart + fileHeader;

      long requestLength = stringData.length() + fileLength;
      connection.setRequestProperty("Content-length", "" + requestLength);
      connection.setFixedLengthStreamingMode((int) requestLength);
      connection.connect();

      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      out.writeBytes(stringData);
      out.flush();

      int progress = 0;
      int bytesRead = 0;
      byte buf[] = new byte[1024];
      BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
      while ((bytesRead = bufInput.read(buf)) != -1) {
        // write output
        out.write(buf, 0, bytesRead);
        out.flush();
        progress += bytesRead;
        // update progress bar
        publishProgress(progress);
      }

       // Write closing boundary and close stream
      out.writeBytes(tail);
      out.flush();
      out.close();

       // Get server response
      BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String line = "";
      StringBuilder builder = new StringBuilder();
      while((line = reader.readLine()) != null) {
        builder.append(line);
      }

    } catch (Exception e) {
      // Exception
    } finally {
      if (connection != null) connection.disconnect();
    }

    return null;
  }

   @Override
  protected void onProgressUpdate(Integer... progress) {
    progressDialog.setProgress((int) (progress[0]));
  }

   @Override
  protected void onPostExecute(Void v) {
    progressDialog.dismiss();
  }

   @Override
  public void onCancel(DialogInterface dialog) {
    cancel(true);
    dialog.dismiss();
  }
}

 

하지만 실제 progressbar 표시하는 부분에서는 

int progress = 0;
      int bytesRead = 0;
      byte buf[] = new byte[1024];
      BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
      while ((bytesRead = bufInput.read(buf)) != -1) {
        // write output
        out.write(buf, 0, bytesRead);
        out.flush();
        progress += bytesRead;
        // update progress bar
        publishProgress(progress);
      }

버퍼에 쓰는 부분이고 실제 서버에 업로드 되는 부분은 아닌거 같습니다. 

버퍼쓰기가 끝나 후에 서버에서 응답하는 시간이 들어가서 마치 앱이 멈춘것처럼 동작하네요.

실제 서버에서 응답을 받을 수 있는 방법이 있나요?

 

 

노예의집 (23,370 포인트) 님이 2016년 4월 8일 질문
노예의집님이 2016년 4월 8일 reshown

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...