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

안드로이드에서 PHP로 업로드

0 추천

업로드에 관련하여 질문드립니다.

httpURLConnection를 이용하여 php서버쪽에 파일을 올리고 싶은데요( 어떤 형식의 파일이든 관련없음 )

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button uploadBtn = (Button)findViewById(R.id.uploadBtn);
        uploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doFileUpload();
            }
        });
    }

    private void doFileUpload() {

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmp_1436920364055.jpg";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 10 * 1024 * 1024;
        String responseFromServer = "";
        String urlString = "http://localhost:8080/phpServer/Server.php";

        try {
            System.out.println("errorpoint:1");
            //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(existingFileName)); //error point **
            System.out.println("errorpoint:2");
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            System.out.println("errorpoint:3");
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            System.out.println("errorpoint:4");
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            System.out.println("errorpoint:5");
            conn.setRequestMethod("POST");
            System.out.println("errorpoint:6");
            conn.setRequestProperty("Connection", "Keep-Alive");
            System.out.println("errorpoint:7");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            System.out.println("errorpoint:8");


            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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);
            // close streams
            Log.e("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }

        //------------------ read the SERVER RESPONSE
        try {

            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {

                Log.e("Debug", "Server Response " + str);

            }

            inStream.close();

        } catch (IOException ioex) {
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
    }
}

php 소스입니다 ( 이부분은 인터넷에서 그대로 옮겼습니다 )

<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 2015-07-15
 * Time: 오후 2:54
 */
echo "phpServer";

$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
        " has been uploaded";
    chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
    echo "target_path: " .$target_path;
}
?>

아무쪼록 부족한 초보개발자를 도와주십사합니다 ㅎㅎ;

개발자01 (120 포인트) 님이 2015년 7월 15일 질문
현재 errorpoint:1까지 출력됩니다

1개의 답변

0 추천
Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmp_1436920364055.jpg";

이 파일이 있는지 확인하시고.

 

적어도 1번이후 로그가 진행이 안되면 에러로그가 나올텐데, 그거라도 적혀있어야 되는거 아닌가 싶은데요.
개발자초심 (21,220 포인트) 님이 2015년 7월 15일 답변
...