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

안드로이드 사진 서버로 전송

0 추천

안녕하세요

찍은 사진을 갤러리에 저장하지 않고 바로 서버로 보내려고 하는데요

커넥션은 잘 되서 200뜨는데 무슨 이유인지 전송이 되지를 않아서요.

stackoverflow에 있는 코드 조금 변경해서 쓰고 있는데 조언 부탁드립니다.

밑에 코드에서 sourceFileUri는 /storage/emulated/0/Android/data/com.example.machinelearning/files/Pictures/TEST_20190407_180919_1627885054.JPG 요런식입니다.

php파일

<?php
$uploads_dir = 'upload/';
if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
  $tmp_name = $_FILES['bill']['tmp_name'];
  $pic_name = $_FILES['bill']['name'];
  move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
}
else{
  echo "File not uploaded successfully.";
}
?>

안드로이드

private class UpLoadFileAsync extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            try {
                String sourceFileUri = (String)params[2];

                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
                File sourceFile = new File(sourceFileUri);

                if (sourceFile.isFile()) {

                    try {
                        String upLoadServerUri = "http://15.164.99.65/server.php";

                        // open a URL httpURLConnectionection to the Servlet
                        FileInputStream fileInputStream = new FileInputStream(
                                sourceFile);
                        URL url = new URL(upLoadServerUri);

                        // Open a HTTP httpURLConnectionection to the URL
                        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                        httpURLConnection.setDoInput(true); // Allow Inputs
                        httpURLConnection.setDoOutput(true); // Allow Outputs
                        httpURLConnection.setUseCaches(false); // Don't use a Cached Copy
                        httpURLConnection.setRequestMethod("POST");
                        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
//                        httpURLConnection.setRequestProperty("ENCTYPE",
//                                "multipart/form-data");
                        httpURLConnection.setRequestProperty("Content-Type",
                                "multipart/form-data; boundary=" + boundary);
                        httpURLConnection.setRequestProperty("bill", sourceFileUri);
                        DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\"" + sourceFileUri + "\"" + lineEnd);

                        dos.writeBytes(lineEnd);

                        // create a buffer of maximum size
                        bytesAvailable = fileInputStream.available();

                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];

                        // read file and write it into form...
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                        while (bytesRead > 0) {

                            dos.write(buffer, 0, bufferSize);
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math
                                    .min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0,
                                    bufferSize);

                        }

                        // send multipart form data necesssary after file
                        // data...
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens
                                + lineEnd);

                        // Responses from the server (code and message)
                        int serverResponseCode = httpURLConnection.getResponseCode();
                        String serverResponseMessage = httpURLConnection
                                .getResponseMessage();
                        System.out.println(serverResponseMessage);

                        System.out.println("SERVER RESPONSE CODE " + serverResponseCode);
                        if (serverResponseCode == 200) {
                            System.out.println("SUCCESS CODE 200");

//                            messageText.setText(msg);
//                            Toast.makeText(ctx, "File Upload Complete.",
//                                  Toast.LENGTH_SHORT).show();
//
//                             recursiveDelete(mDirectory1);

                        }

                        // close the streams //
                        fileInputStream.close();
                        dos.flush();
                        dos.close();

                    } catch (Exception e) {

                        // dialog.dismiss();
                        e.printStackTrace();

                    }
                    // dialog.dismiss();

                } // End else block


            } catch (
                    Exception ex) {
                // dialog.dismiss();

                ex.printStackTrace();
            }
            return "Executed";
        }

 

pandroooid (120 포인트) 님이 2019년 4월 7일 질문

답변 달기

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