파일 업로드

지극히 개인적으로
써봤던 것들을 잊지 않기위해 옮겨 놓은 곳이니
참고하실분은 참고하시길...


 --*
  * 데이터 업데이트 시 비동기 방식으로 처리하기 위한 클래스
  --
 public class UpdateTask extends AsyncTask<Void, Integer, Boolean> {
  // private ProgressDialog dialog;

  // private MyProgressDialog mDialog;

  private Context context;
  ProgressDialog progressDialog;

  public UpdateTask(Context cont) {
   this.context = cont;

  }

  @Override
  protected void onPreExecute() {
   
   Utils.lockScreenOrientation((Activity)context);
   
   Log.i("onPreExecute", "Start [UpdataTask]");
   progressDialog = new ProgressDialog(InformationContent.this);
   progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
   progressDialog.setMessage("잠시만 기다려 주십시오");
   progressDialog.setCancelable(false);
   progressDialog.show();
   //System.out.println("나탔음01");
  }

  @Override
  protected Boolean doInBackground(Void... params) {// execute에서 전달한 값을

   boolean updata = false;
   //System.out.println("나탔음02");
   try {
    int bytesAvailable = 0;
    if (attachedFilePath01 != null) {
     mFileInputStream = new FileInputStream(attachedFilePath01);
     bytesAvailable = mFileInputStream.available();
    }

    String title = "";
    if (content.getText().toString().length() <= 20) {
     title = content.getText().toString();
    } else {
     title = content.getText().toString().substring(0, 20);
    }

    StringBuffer sbf = new StringBuffer("url.php");
    sbf.append("cont_div=");
    sbf.append("T");
    sbf.append("&title=");
    sbf.append(URLEncoder.encode(title, "euc-kr"));
    sbf.append("&name=");
    sbf.append(URLEncoder.encode(name.getText().toString(),
      "euc-kr"));
    sbf.append("&phone=");
    sbf.append(URLEncoder.encode(phone.getText().toString(),
      "euc-kr"));
    sbf.append("&email=");
    sbf.append(URLEncoder.encode(email.getText().toString(),
      "euc-kr"));
    sbf.append("&addr=");
    sbf.append(URLEncoder.encode(address.getText().toString(),
      "euc-kr"));
    sbf.append("&content=");
    sbf.append(URLEncoder.encode(content.getText().toString(),
      "euc-kr"));
    sbf.append("&pri_use_yn=Y&liveshot_yn=Y&type=03");

    String url = sbf.toString();
    URL infoUrl = new URL(url);

    Log.d("File Up", "mFileInputStream is " + mFileInputStream);

    // open connection
    HttpURLConnection conn = (HttpURLConnection) infoUrl
      .openConnection();

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type",
      "multipart/form-data;boundary=" + boundary);

    // ****************************이곳이 파일첨부한거
    // 보내기?****************************
    // write data

    DataOutputStream dos = new DataOutputStream(
      conn.getOutputStream());

    dos.writeBytes(twoHyphens + boundary + lineEnd);

    // 여기부터
    dos.writeBytes("Content-Disposition:form-data;name=\"file1\";filename=\""
      + attachedFilePath01 + "\"" + lineEnd);
    if (attachedFilePath02 != null) {
     mFileInputStream02 = new FileInputStream(attachedFilePath02);
     bytesAvailable += mFileInputStream02.available();
     dos.writeBytes(twoHyphens + boundary + lineEnd);
     dos.writeBytes("Content-Disposition:form-data;name=\"file2\";filename=\""
       + attachedFilePath02 + "\"" + lineEnd);
    }
    if (attachedFilePath03 != null) {
     mFileInputStream03 = new FileInputStream(attachedFilePath03);
     bytesAvailable += mFileInputStream03.available();
     dos.writeBytes(twoHyphens + boundary + lineEnd);
     dos.writeBytes("Content-Disposition:form-data;name=\"file3\";filename=\""
       + attachedFilePath03 + "\"" + lineEnd);
    }
    // 여기까지인가
    dos.writeBytes(lineEnd);
    int maxBufferSize = 1024;
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    byte[] buffer = new byte[bufferSize];

    if (attachedFilePath01 != null) {
     int bytesRead = mFileInputStream
       .read(buffer, 0, bufferSize);
     Log.d("File Up", "image byte is " + bytesRead);
     // Read 파일
     int i = 0;
     // //System.out.println("byte==========" + bytesRead);
     // //System.out.println("bufferSize==========" + bufferSize);
     //System.out.println("buffer=======" + buffer);
     // //System.out.println("Size=========" + )

     // 파일 바이트 크기 구하기?
     int fileSize = 0;

     if (attachedFilePath01 != null) {
      File attachedFilePath01Length = new File(
        attachedFilePath01);
      fileSize += attachedFilePath01Length.length();
      if (attachedFilePath02 != null) {
       File attachedFilePath02Length = new File(
         attachedFilePath02);
       fileSize += attachedFilePath02Length.length();
      }
      if (attachedFilePath03 != null) {
       File attachedFilePath03Length = new File(
         attachedFilePath03);
       fileSize += attachedFilePath03Length.length();
      }
      //System.out.println("fileSize===========" + fileSize);

      progressDialog.setMax(fileSize / maxBufferSize);
     }
     //System.out.println("나탔음08");

     while (bytesRead > 0) {
      dos.write(buffer, 0, bufferSize);
      bytesAvailable = mFileInputStream.available();
      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      bytesRead = mFileInputStream
        .read(buffer, 0, bufferSize);
      i++;
      publishProgress(i);
     }
     dos.writeBytes(lineEnd);
     dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
     // close streams
     Log.e("File Up", "File is written");
     mFileInputStream.close();
    }

    dos.flush(); // 버퍼에 있는 값을 모두 밀어냄
    // 웹서버에서 결과를 받아 EditText 컨트롤에 보여줌
    // int ch;
    // InputStream is = conn.getInputStream();
    // StringBuffer b = new StringBuffer();

    // while ((ch = is.read()) != -1) {
    // b.append((char) ch);
    --
     * i++; publishProgress(i);
     --
    // //System.out.println("while count===========" + i++);
    // }
    // String s = b.toString();
    // Log.e("File Up", "result = " + s);
    // //System.out.println("여기가 에러냐?");
    // mEditEntry.setText(s);
    // //System.out.println("mEditEntry========" + s);
    dos.close();
    updata = true;
    infoState = Cons.SEND_TYPE_COMPLETE;
    //System.out.println("file01 === " + attachedFilePath01);
    //System.out.println("file02 === " + attachedFilePath02);
    //System.out.println("file03 === " + attachedFilePath03);
   } catch (Exception e) {
    Log.d("File Up", "exception " + e.getMessage());
    updata = false;
    infoState = Cons.SEND_TYPE_FAILED;
   }
   return updata;
  }

  @Override
  protected void onProgressUpdate(Integer... progress) {
   // TODO Auto-generated method stub
   // super.onProgressUpdate(values);
   // progressDialog.setProgress(progress[0]);

   progressDialog.setProgress(progress[0]);
  }

  protected void onPostExecute(Boolean updata) {
   --
    * dialog.dismiss(); Log.i("onPostExecute", "End [UpdataTask]");
    --
   progressDialog.dismiss();
   Utils.unlockScreenOrientation((Activity)context);
   // com.nemodream.android.utils.date.Date ut = new Date();

   Date currentTime = new Date();

   SimpleDateFormat formatter = new SimpleDateFormat(
     "yyyy.MM.dd HH:mm:ss");
   String dTime = formatter.format(currentTime);
   //System.out.println(dTime);

   if (updata == true) {
    dbm.insertInfoBox(type, phone.getText().toString(), email
      .getText().toString(), address.getText().toString(),
      content.getText().toString(),
      name.getText().toString(), attachedFilePath01,
      uri01type, attachedFilePath02, uri02type,
      attachedFilePath03, uri03type, infoState, dTime);
    alert_ok();
   } else {
    dbm.insertInfoBox(type, phone.getText().toString(), email
      .getText().toString(), address.getText().toString(),
      content.getText().toString(),
      name.getText().toString(), attachedFilePath01,
      uri01type, attachedFilePath02, uri02type,
      attachedFilePath03, uri03type, infoState, dTime);
    alert_fail();
   }
  }

  @Override
  protected void onCancelled() {
   // TODO Auto-generated method stub
   progressDialog.dismiss();
   Utils.unlockScreenOrientation((Activity)context);
  }

 }

by 송지훈 | 2011/08/30 04:39 | android | 트랙백 | 덧글(0)

◀ 이전 페이지다음 페이지 ▶