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

카메라 촬영 이미지 서버 업로드 문제

0 추천

아래와 같이 업로드 코드를 AsyncTask 안에서 호출하도록 작성해서 

카메라로 촬영한 이미지 데이터를 업로드 해야 하는데 

디버깅으로 중단점 잡은 후 계속 실행하면 서버에 파일이 저장되고 

그냥 실행하면 서버에 파일이 저장이 되질 않네요.

 

public void imgUpload(byte[] data)
{
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;
    Bitmap orgImage = BitmapFactory.decodeByteArray(data, 0, data.length, options);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    orgImage.compress(Bitmap.CompressFormat.JPEG, 100, stream) ;
    data = stream.toByteArray();

    if(data == null)
        return;

    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String filename = "IMG_" + timestamp + ".jpg";

    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

    try {
        URL url = new URL("서버/UploadHandler.ashx");
        Log.i(TAG, "서버/UploadHandler.ashx" );
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        // open connection
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setDoInput(true); //input 허용
        con.setDoOutput(true);  // output 허용
        con.setUseCaches(false);   // cache copy를 허용하지 않는다.
        con.setRequestMethod("POST");
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        // write data
        DataOutputStream dos = new DataOutputStream(con.getOutputStream());
        Log.i(TAG, "Open OutputStream");
        dos.writeBytes(twoHyphens + boundary + lineEnd);

        // 파일 전송시 파라메터명은 file1 파일명은 camera.jpg로 설정하여 전송
        dos.writeBytes("Content-Disposition:form-data;name=\"uploadedfile\";filename=\"" + filename + "\"" + lineEnd);

        dos.writeBytes(lineEnd);
        dos.write(data, 0, data.length);
        Log.i(TAG, data.length + "bytes written");
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush(); // finish upload...  <-- 반드시 여기에 중단점이 있어야 서버에 파일이 저장됩니다. 

    } catch (Exception e) {
        Log.i(TAG, "exception " + e.getMessage());
        // TODO: handle exception
    }
}
Jakee (150 포인트) 님이 2016년 2월 4일 질문
Jakee님이 2016년 2월 4일 수정

1개의 답변

0 추천
 
채택된 답변
업로드 후 서버 응답을 기다리는 코드를 추가해보세요.

근본적으로는 HttpUrlConnection을 직접 쓰지 마시고 관련 작업을 하는 라이브러리를 사용하세요.
익명사용자 님이 2016년 2월 4일 답변
Jakee님이 2016년 2월 4일 채택됨
관심가져주셔서 감사합니다. 가르쳐 주신대로 한번 수정해보겠습니다.
해결했습니다. 정말 감사합니다. 지금은 급한데로 기능만 구현하느라 HttpUrlConnection 을 직접 썼지만 추후에 라이브러리를 사용하는 방법으로 바꿔야겠네요..
...