2010-11-28 6 views
1

내 안드로이드 장치에서 파일을 PHP 서버로 업로드하려고합니다. 같은 질문을 가진 실이 있지만 다른 방법을 사용하고 있습니다. 내 Android 측 코드가 제대로 작동하고 오류 메시지가 표시되지 않지만 서버에서 파일을 수신하지 않습니다. 여기에 내 샘플 코드가 있습니다. 온라인으로 찾았습니다. 아파치가 실행안드로이드에서 PHP 서버로 사진 업로드

<?php 

$target_path = "uploads/"; 

$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!"; 
    } 
    ?> 

을 다음과 같이

import java.io.FileInputStream; 
import android.app.Activity; 
import android.os.Bundle; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.IOException; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import android.util.Log; 

public class uploadfile extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    doFileUpload(); 
} 

private void doFileUpload(){ 
HttpURLConnection conn = null; 
DataOutputStream dos = null; 
DataInputStream inStream = null;  
String exsistingFileName = "/sdcard/def.jpg"; 

// Is this the place are you doing something wrong. 
String lineEnd = "rn"; 
String twoHyphens = "--"; 
String boundary = "*****"; 

int bytesRead, bytesAvailable, bufferSize; 
byte[] buffer; 
int maxBufferSize = 1*1024*1024; 
String responseFromServer = ""; 
String urlString = "http://192.168.1.6/index.php"; 

try 
    { 
     //------------------ CLIENT REQUEST 
     Log.e("MediaPlayer","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); 

             dos = new DataOutputStream(conn.getOutputStream()); 
             dos.writeBytes(twoHyphens + boundary + lineEnd); 
             dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" 
                  + exsistingFileName + "\"" + lineEnd); 
             dos.writeBytes(lineEnd); 
             Log.e("MediaPlayer","Headers are written"); 

             // 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("MediaPlayer","File is written"); 
             fileInputStream.close(); 
             dos.flush(); 
             dos.close(); 

        } 

     catch (MalformedURLException ex) 

    { 

      Log.e("MediaPlayer", "error: " + ex.getMessage(), ex); 

     } 



     catch (IOException ioe) 

     { 

      Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe); 

     } 

     //------------------ read the SERVER RESPONSE 
     try { 
      inStream = new DataInputStream (conn.getInputStream()); 
      String str; 

      while ((str = inStream.readLine()) != null) 
      { 
       Log.e("MediaPlayer","Server Response"+str); 
      } 

      inStream.close(); 
     } 

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

    } 
    } 

내 PHP는 서버 측 코드입니다. 서버를 실행할 때이 오류 메시지가 나타납니다. 파일을 업로드하는 중 오류가 발생했습니다. 다시 시도하십시오. 이클립스에서 로그 데이터를 확인하고 내가 소켓 문제라고 생각하지만 확실하지 않습니다. 누군가가 해결책을 안다면 도와주세요.

11-28 05:37:55.310: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol 
+0

변경된 태그

String lineEnd = "rn"; 

교체 -이와 아무로 표시되지 않습니다 PHP - 당신은 전통적인 브라우저를 사용하여 간단한 테스트 페이지로 이것을 확인할 수 있어야합니다. – symcbean

+0

하지만이 PHP 코드는 PHP에있는 PHP 코드라고 생각합니다. – SilentCoder

+0

이 코드를 시도했는데 POST 요청에서 아무 파일도 전송되지 않는다고 말할 수 있습니다. var_dump ($ _ FILES);를 사용하여 테스트했습니다. – Richard

답변

2

서버가 클라이언트에 응답하지 않는 것으로 보입니다. 안드로이드 애플리케이션을 통해 ftp 연결을 사용하여 업로드를 시도하고, 작동하는 경우 연결 및 쓰기 가능한 디렉토리 수용시 Apache 구성을 확인하십시오. 비슷한 문제가 생겼을 때 디렉토리에 쓰기 권한이 없다는 것이 밝혀졌습니다.

Java 또는 Apache의 오류입니까? 올바른 이스케이프 시퀀스에 대한 다음과 같은 방법으로 코드

+0

ftp clien을 연결하려고합니다. 서버 연결에 실패했습니다. 서버를 실행하는 방법에 혼란이 있습니다. 브라우저에서 아파치를 실행하고 서버 URL을 열어야합니까? 아니면 다른 작업을해야합니까? 오류 메시지는 일식 로그에 있습니다. – SilentCoder

+0

제안 사항 plz ?? – SilentCoder

+0

데이터를 FTP로 보내려는 경우 Apache와 관련이 없으므로 FTP 서버를 실행해야합니다. PHP 파일을 업로드하지 않고도 "캐치"할 수 있습니다. 다른 손으로 PHP를 사용하여 업로드하려고한다면 "_POST"를 사용하여 Ja에서 패스해야합니다 당신의 PHP 파일 이름. 업로드 한 파일 이름을 알 수없는 것처럼 보이는 코드는 올바른 위치에 있습니다. 희망이 도움이됩니다. –

1

변경 :

String lineEnd = "\r\n";