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

php 이용하여 서버에 텍스트와 이미지 저장 부분 질문입니다

0 추천
  • <?php

    try{

     $content = "";
     $img = "";

     //앱에서 보내는 데이터를 post 방식으로 취득
     $content =   $_POST["content"];
     $img =    $_POST["img"];
     
    이러한 방식으로 php 를 저장 하였습니다

    content 에는 글을 저장 하고
    img 부분에는 이미지를 저장 하려고 합니다


       public void HttpFileUpload(String urlString, String params, String fileName) {

       

        try{

          //선택한 파일의 절대 경로를 이용해서 파일 입력 스트림 객체를 얻어온다.

          FileInputStream mFileInputStream = new FileInputStream(fileName);

          //파일을 업로드할 서버의 url 주소를이용해서 URL 객체 생성하기.

          URL connectUrl = new URL(urlString);

          //Connection 객체 얻어오기.

          HttpURLConnection conn = (HttpURLConnection)connectUrl.openConnection(); 

          conn.setDoInput(true);//입력할수 있도록

          conn.setDoOutput(true); //출력할수 있도록

          conn.setUseCaches(false);  //캐쉬 사용하지 않음

         

          //post 전송

          conn.setRequestMethod("POST");

          //파일 업로드 할수 있도록 설정하기.

          conn.setRequestProperty("Connection", "Keep-Alive");

          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

         

          //DataOutputStream 객체 생성하기.

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

          //전송할 데이터의 시작임을 알린다.

          dos.writeBytes(twoHyphens + boundary + lineEnd);

          dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName+"\"" + lineEnd);

          dos.writeBytes(lineEnd);

          //한번에 읽어들일수있는 스트림의 크기를 얻어온다.

          int bytesAvailable = mFileInputStream.available();

          //byte단위로 읽어오기 위하여 byte 배열 객체를 준비한다.

          byte[] buffer = new byte[bytesAvailable];

          int bytesRead = 0;

          // read image

          while (bytesRead!=-1) {

          //파일에서 바이트단위로 읽어온다.

          bytesRead = mFileInputStream.read(buffer);

          if(bytesRead==-1)break; //더이상 읽을 데이터가 없다면 빠저나온다.

              Log.d("Test", "image byte is " + bytesRead);

              //읽은만큼 출력한다.

          dos.write(buffer, 0, bytesRead);

          //출력한 데이터 밀어내기

          dos.flush();

          }

          //전송할 데이터의 끝임을 알린다.

          dos.writeBytes(lineEnd);

          dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

          //flush() 타이밍??

          //dos.flush();

          dos.close();//스트림 닫아주기 

          mFileInputStream.close();//스트림 닫아주기.

          // get response

          int ch;

          //입력 스트림 객체를 얻어온다.

          InputStream is = conn.getInputStream();

          StringBuffer b =new StringBuffer();

          while( ( ch = is.read() ) != -1 ){

          b.append( (char)ch );

          }

          String s=b.toString();

          Log.e("Test", "result = " + s);

          } catch (Exception e) {

            Log.d("Test", "exception " + e.getMessage());

            Toast.makeText(this,"업로드중 에러발생!", 0).show();

          } 

      }

       

    }


    comment 랑 Img 테그에 값을 저장 하려면
    이 코드에서 어디 부분을 수정 해야 할까요?
     dos.writeBytes(twoHyphens + boundary + lineEnd);

          dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName+"\"" + lineEnd);

          dos.writeBytes(lineEnd);
    이 부분을 수정해야 하나요???

김니이 (420 포인트) 님이 2014년 7월 10일 질문
김니이님이 2014년 7월 10일 수정

1개의 답변

0 추천

Form-based File Upload in HTML

 

$comm_user =

$comm_content
이 두 부분에 서버에 저장 할 사용자 이름과 글 내용을 저장을 시켜야 하는 건가요?

해당 코드 밑을 보니 comm_user 와 comm_content 라는 이름으로 post 데이터를 대입 시키는 걸 보면 아실 것 같습니다.

$comm_user = $_POST["comm_user"];
$comm_content = $_POST["comm_content"];

comm_content 는 html 의 textarea 부분 정도의 데이터를 담는 변수 인것 이고 file 업로드는 다릅니다.

file 에 해당하는 변수라면 $_FILES 를 전달 받아야 됩니다.

 

aucd29 (218,390 포인트) 님이 2014년 7월 10일 답변
$content =            $_POST["content"];
$img =                $_POST["img"];
제가 글을 잘못 올렸네요 위에 방식입니다
content 부분에는 글 내용을 저장하고
img 부분에는 이미지를 저장 하려고 합니다
content 와 img 이 테그에 값을 저장 하려면 위에 코드에서 어디를 수정해야되나요>?

댓글에 적혀 있듯이 $_POST 로 전달 받는게 아니고 업로드는 $_FILES 로 전달 받아야 합니다. http://php.net/manual/kr/features.file-upload.post-method.php
...