2011-05-11 2 views
0

나는 안드로이드에서 PHP 서버로 이미지를 업로드하는 앱을 만들고 PHP 서버는 요청에 대한 응답으로 URL을 반환합니다. 나는 아이폰을 위해 잘 작동하는 PHP 서버 측에서 아무 문제도 체크하지 않았다. 하지만 안드로이드에서 나는 응답을 얻을 수 없습니다. 내 이미지가 업로드되지 않은 PHP 서버를 확인했습니다. 나는 코드의 문제점과 응답을 얻는 방법을 모른다. 필요한 설정이 있습니까? 내 코드 :이미지가 PHP 서버에 업로드되지 않았습니다. android에서 servre의 응답이 없습니다

public class upload extends Activity { 
InputStream is; 
@Override 
public void onCreate(Bundle icicle) { 
super.onCreate(icicle); 
setContentView(R.layout.main); 
Bitmap bitmapOrg = BitmapFactory.decodeFile("/sdcard/imageq.png"); 
ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
bitmapOrg.compress(Bitmap.CompressFormat.PNG, 90, bao); 
byte [] ba = bao.toByteArray(); 
String ba1=Base64.encodeBytes(ba); 
ArrayList<NameValuePair> nameValuePairs = new 
ArrayList<NameValuePair>(); 
nameValuePairs.add(new BasicNameValuePair("image",ba1)); 
try{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://xxxxxxxxxx/xxxxxx/upload.php"); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    HttpResponse response = httpclient.execute(httppost); 
    Log.e("uri",""+httppost.getURI()); 
    Log.e("response",""+response); 
    HttpEntity entity = response.getEntity(); 
    is = entity.getContent(); 
    Log.e("is",""+is); 
}catch(Exception e){ 
Log.e("log_tag", "Error in http connection "+e.toString()); 
} 
} 
} 

나는 http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/ 내 로그 고양이 정보에서 위의 코드를 얻을 :

05-11 10:09:39.488: ERROR/uri(1894): http://xxxxxxxxxx/xxxxxx/upload.php 
05-11 10:09:39.488: ERROR/response(1894): [email protected] 
05-11 10:09:39.495: ERROR/is(1894): [email protected] 

내가 getURI 그것이 내가 httppost = 새로운 HttpPost에주고 무엇을 반환 인쇄 ("... "). 이것은 서버로부터의 실제 응답이 아닙니다. 도와주세요.

답변

0
package com.telubi.connectivity; 

import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

import android.util.Log; 

import com.cipl.TennisApp.Login; 

public class FileUploader { 

    private String Tag = "UPLOADER"; 
    private String urlString;// = "YOUR_ONLINE_PHP"; 
    HttpURLConnection conn; 
    String exsistingFileName; 
    public String result; 

    public String uploadImageData(String serverImageTag) {// Server image tag 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     try { 
      // ------------------ CLIENT REQUEST 

      Log.e(Tag, "Inside second Method"); 

      FileInputStream fileInputStream = new FileInputStream(new File(
        exsistingFileName)); 

      // open a URL connection to the Servlet 

      URL url = new URL(urlString); 

      // Open a HTTP connection to the URL 

      conn = (HttpURLConnection) url.openConnection(); 

      // Allow Inputs 
      conn.setDoInput(true); 

      // Allow Outputs 
      conn.setDoOutput(true); 

      // Don't use a cached copy. 
      conn.setUseCaches(false); 

      // Use a post method. 
      conn.setRequestMethod("POST"); 

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

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

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

      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      if (serverImageTag.equalsIgnoreCase("courtImage")) { 
       dos.writeBytes("Content-Disposition: post-data; name=courtImage[];filename=" 
         + exsistingFileName + "" + lineEnd); 
      } else if (serverImageTag.equalsIgnoreCase("userImage")) { 
       dos.writeBytes("Content-Disposition: post-data; name=userImage[];filename=" 
         + exsistingFileName + "" + lineEnd); 
      } 
      dos.writeBytes(lineEnd); 

      Log.e(Tag, "Headers are written"); 

      // create a buffer of maximum size 

      int bytesAvailable = fileInputStream.available(); 
      int maxBufferSize = 1000; 
      // int bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      byte[] buffer = new byte[bytesAvailable]; 

      // read file and write it into form... 

      int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable); 

      while (bytesRead > 0) { 
       dos.write(buffer, 0, bytesAvailable); 
       bytesAvailable = fileInputStream.available(); 
       bytesAvailable = Math.min(bytesAvailable, maxBufferSize); 
       bytesRead = fileInputStream.read(buffer, 0, bytesAvailable); 
      } 

      // send multipart form data necessary after file data... 

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

      String serverResponseMessage = conn.getResponseMessage(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(
        conn.getInputStream())); 

      // String serverResponseCode = conn. 
      // String serverResponseMessage = conn.getResponseMessage(); 

      while ((result = rd.readLine()) != null) { 

       Log.v("result", "result " + result); 

        Login.fbResponse = result; 

      } 
      // close streams 
      Log.e(Tag, "File is written"); 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 
      rd.close(); 
     } catch (MalformedURLException ex) { 
      Log.e(Tag, "error: " + ex.getMessage(), ex); 
     } 

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

     // Parsing has finished. 
     return result; 
    } 

    public FileUploader(String existingFileName, String urlString) { 

     this.exsistingFileName = existingFileName; 
     this.urlString = urlString; 

    } 

} 

난 당신이 파일을 업로드 업로드 및 대상 URL (PHP 서버 URL) 원하는 FilsUploader 생성자 패스 파일 이름을 찾아이 코드에 포스트 방법으로 PHP 서버에 장치에서 이미지를 업로드 할이 코드를 사용하고 .I 이것이 도움이되기를 바랍니다.

+0

저는 그것을 구현합니다. 하지만 난 'serverImageTag'과 uploadImageData 함수가 호출되는 곳이 무엇인지 의심 스럽다. –

+0

uploadImageData이 함수 호출은 FileUploader 클래스의 객체를 생성 한 직후에 호출되며 serverImageTag는 함수 및 조건에 대해 제거 할 필요가없는 경우 PHP 서버에서 제공 한 태그입니다. – DynamicMind

관련 문제