2011-02-09 5 views
1

Android 코드에서 PHP 웹 서버 코드로 비디오를 업로드하려고하는데 성공하지 못합니다. 업로드 작업을 수행하려면 다음 link을 참조하고 있지만 Android 코드에서 다음과 같은 응답이 표시되지만 PHP 서버에서 파일을 찾을 수 없습니다.Android에서 PHP로 비디오를 업로드하는 코드

내가 php.ini 파일에 값을 설정처럼 많은 것을 확인했다

DEBUG/ServerCode(29484): 200 
DEBUG/serverResponseMessage(29484): OK 

안드로이드 응답. 안드로이드에서 이미지를 업로드 할 수 있지만 안드로이드에서 이미지를 업로드 할 수는 있지만, 나는 ByteArray 인코딩 된 64 비트를 보내고 있습니다. 인코딩 된 이미지를 만들 수있는 기성품 인 ByteArray이 기성품입니다.

그러나이 코드는 이미지가 아닌 다른 파일의 경우에도 작동하지 않습니다.

이전에 비슷한 일을 한 적이 있다면 저를 안내해주십시오.

PHP의 내가 사용하고 코드 :

<?php 

    $target_path = "./upload/"; 

    $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"; 
    } 
    else 
    { 
     echo "There was an error uploading the file, please try again!"; 
    } 
?> 

안드로이드 코드 내가 사용하고 :

public void videoUpload() 
{ 
    HttpURLConnection connection = null; 
    DataOutputStream outputStream = null; 
    DataInputStream inputStream = null; 


    String pathToOurFile = "/sdcard/video-2010-03-07-15-40-57.3gp"; 
    String urlServer = "http://10.0.0.15/sampleWeb/handle_upload.php"; 
    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 

    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1*1024*1024; 

    try 
    { 
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); 

    URL url = new URL(urlServer); 
    connection = (HttpURLConnection) url.openConnection(); 

    // Allow Inputs & Outputs 
    connection.setDoInput(true); 
    connection.setDoOutput(true); 
    connection.setUseCaches(false); 

    // Enable POST method 
    connection.setRequestMethod("POST"); 

    connection.setRequestProperty("Connection", "Keep-Alive"); 
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary"); 

    outputStream = new DataOutputStream(connection.getOutputStream()); 
    outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile); 
    outputStream.writeBytes(lineEnd); 

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

    // Read file 
    bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

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

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

    // Responses from the server (code and message) 
    int serverResponseCode = connection.getResponseCode(); 
    String serverResponseMessage = connection.getResponseMessage(); 
    Log.d("ServerCode",""+serverResponseCode); 
    Log.d("serverResponseMessage",""+serverResponseMessage); 
    fileInputStream.close(); 
    outputStream.flush(); 
    outputStream.close(); 
    } 
    catch (Exception ex) 
    { 
     ex.printStackTrace(); 
    } 
} 
+0

이 방법을 쓰기 당신은 당신의 코드에서 몇 가지 실수를했다. 코드를 게시하십시오. 따라온 블로그는 괜찮은 것처럼 보이지만 블로그 기사를 '따라 다니는 동안 실수를했을 수도 있습니다. –

+0

안녕하세요 Sarwar 저는 안드로이드와 PHP 모두의 코드를 업데이트했습니다. 많이 시도했지만이 작은 코드에서 문제를 찾을 수 없습니다 – Abhi

+0

Abhishek, 안드로이드에서 서버에 비디오를 업로드하는 것에 대한 해결책을 얻었습니까? 나는 또한 동일을 찾고있다. 혹시 어떤 생각이 든다면 나와 공유하십시오. –

답변

2

내 자바가 조금 끈적 끈적하지만 ....

그것은 연결처럼 보인다. getResponseCode는 HTTP 상태 코드 만 반환하고 connection.getResponseMessage는 HTTP 상태 메시지 만 반환하지만 PHP는 이러한 값을 조작하지 않습니다. 당신은 시도 할 수 있습니다 :

$target_path = "./upload/"; 
$src = $_FILES['uploadedfile']['name']; 

$target_path .= basename($src); 

if(file_exists($src) 
     && 
     && move_uploaded_file($src, $target_path) 
    ) { 
    echo "The file ".basename($_FILES['uploadedfile']['name'])." has been uploaded"; 
} else { 
    header("Server Error", true, 503); 
    echo "There was an error uploading the file, please try again!"; 
    $msg = "src size ? " 
     . filesize($src) . "\n dest dir writable ?" 
     . is_writeable(dirname($target_path)) ? "Y\n" : "N\n" 
     . "FILES contains :\n"; 
     . var_export($_FILES,true); 
    // now write $msg somwhere you can read it 
} 

이 무엇이 잘못되었는지 좁히는 데 도움이 shuld

+0

코드에 대한 감사의 symcbean은 코드 u의 마지막 세 줄이 올바른 구문 방식인지 확인합니다. – Abhi

+0

또한이 코드를 실행하여 동일한 응답 200 및 OK를 받고 있습니다 – Abhi

+0

그런 다음 파일을 읽고 이동했습니다. – symcbean

1
private String mString; 
private Uri image_uri; 
private String response;  
private HttpURLConnection conn = null; 
private DataOutputStream dos = null; 
private String lineEnd = "\r\n"; 
private String twoHyphens = "--"; 
private String boundary = "*****"; 
private int bytesRead, bytesAvailable, bufferSize; 
private byte[] buffer; 
private String url_for_image_upload = "your_web_api_put_here"; 
private int maxBufferSize = 1 * 1024 * 1024; 

// 다음 버튼의 온 클릭 리스너

mString = getRealPathFromURI (image_uri)에서이 두 가지 방법을 문의;

ImageUpload();

// 당신이 당신의 php.ini 괜찮 보장 경우, 여기

private void ImageUpload() { 

    Toast.makeText(getApplicationContext(), 
      "Please Wait while uploading Image", Toast.LENGTH_SHORT).show(); 

    try { 
     FileInputStream fileInputStream = new FileInputStream(new File(mString)); 
     URL url = new URL(url_for_image_upload); 

     conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoInput(true); 

     conn.setDoOutput(true); 

     conn.setUseCaches(false); 

     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Connection", "Keep-Alive"); 
     conn.setRequestProperty("Content-Type", 
       "multipart/form-data;boundary=" + boundary); 
     dos = new DataOutputStream(conn.getOutputStream()); 
     dos.writeBytes(twoHyphens + boundary + lineEnd); 
     dos.writeBytes("Content-Disposition: form-data; name=\"img_name\";filename=\"img_name" 
       + "\"" + lineEnd); 
     dos.writeBytes(lineEnd); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     buffer = new byte[bufferSize]; 
     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); 
     } 
     dos.writeBytes(lineEnd); 
     dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
     BufferedReader in = new BufferedReader(new InputStreamReader(
       conn.getInputStream())); 
     Log.d("BuffrerReader", "" + in); 

     if (in != null) { 
      response = convertStreamToString(in); 
      Log.e("FINAL_RESPONSE-LENGTH",""+response.length()); 
      Log.e("FINAL_RESPONSE", response); 
     } 

     fileInputStream.close(); 
     dos.flush(); 
     dos.close(); 

     if (response.startsWith("0")) { 
      Toast.makeText(getApplicationContext(), 
        "Image Uploaded not successfully", Toast.LENGTH_SHORT) 
        .show(); 
     } else { 
      Toast.makeText(getApplicationContext(), 
        "Image Uploaded successfully", Toast.LENGTH_SHORT) 
        .show(); 

     } 

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

} 

public String getRealPathFromURI(Uri contentUri) { 
    String[] proj = { MediaColumns.DATA }; 
    @SuppressWarnings("deprecation") 
    Cursor cursor = managedQuery(contentUri, proj, null, null, null); 
    int column_index = cursor 
      .getColumnIndexOrThrow(MediaColumns.DATA); 
    cursor.moveToFirst(); 

    mString = cursor.getString(column_index); 

    return mString; 

} 

public static String convertStreamToString(BufferedReader is) 
     throws IOException { 
    if (is != null) { 
     StringBuilder sb = new StringBuilder(); 
     String line; 
     try { 

      while ((line = is.readLine()) != null) { 
       sb.append(line).append(""); 
      } 
     } finally { 
      is.close(); 
     } 
     return sb.toString(); 
    } else { 
     return ""; 
    } 
} 
관련 문제