2013-01-22 2 views
2

안드로이드 폰에서 PHP 서버로 img를 업로드하려고합니다. 이안드로이드 - PHP 서버에 업로드 할 때 이미지가 비어 짐

을 손실 데이터 업로드 (파일이 존재를하지만, 0 바이트를 가지고) 때

는하지만 문제가 PHP 측 또는 안드로이드 측에 있는지 잘 모릅니다. 여기

내가 업로드 사용하는 코드입니다

PHP :

<?php 
$base=$_REQUEST['image']; 
$binary=base64_decode($base); 
header('Content-Type: bitmap; charset=utf-8'); 
$file = fopen('uploaded_image.jpg', 'wb'); 
fwrite($file, $binary); 
fclose($file); 
echo 'Image upload complete!!, Please check your php file directory……'; 
?> 

자바 : 여기

private void httpPostFileUpload(String fpath){ 
     HttpURLConnection connection = null; 
     DataOutputStream outputStream = null; 
     DataInputStream inputStream = null; 

     String pathToOurFile = fpath; 
     Log.v("file path",fpath.toString()); 
     String urlServer = "http://leojg.alwaysdata.net/tests/androidConnect/upload_image.php"; 
     //String urlServer = "http://65.182.110.63/public/handle_upload.php"; 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     String fname = ""; 

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

     try 
     { 
      File f = new File(pathToOurFile); 
      fname = f.getName(); 

      FileInputStream fileInputStream = new FileInputStream(f); 

      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="+boundary); 

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

      Log.v("ouput stream",outputStream.toString());    

      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("amanda", "upload async finished, server response : " + serverResponseMessage); 

      fileInputStream.close(); 
      fileInputStream = null; 
      outputStream.flush(); 
      outputStream.close(); 
      outputStream = null; 
      f= null; 



      parent.invokeJs("pictureUploadEnded('" + fname + "')"); 
      //this.delete(fpath); 

     } 
      catch (Exception ex) 
     { 
       Log.d("amanda", "exception uploading image : " + ex.getMessage()); 
     }  
} 

당신이 볼 수있는 IMG가 저장되는 http://leojg.alwaysdata.net/tests/androidConnect/

해결책 :

<?php 
$target_path = "./"; 
$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!"; 
} 
?> 

답변

1

$_REQUEST에서 다중 부분/양식 데이터를 가져올 수 없습니다. 시도하십시오 $_FILES. http://php.net/manual/en/features.file-upload.php

+0

변경되었지만 같은 문제가 있습니다 – leojg

+0

@leojg -'$ _REQUEST'를'$ _FILES'로 변경할 수 없습니다. PHP가 업로드하는 임시 파일에 액세스해야합니다 (PHP는 임시 파일이'$ _FILES' 배열에 있음을 알려줍니다). 그런 다음,'move_uploaded_file'을 사용하여 원하는 곳에 이동할 수 있습니다. – nickb

+0

감사합니다. 모든 코드를 변경해야했지만 이제는 작동합니다. 위의 수정 사항을 게시합니다. – leojg

1

PHP 업로드를 사용해야합니까? 나는 항상 FTP 업로드 (백엔드가 FileZilla를 사용할 수 있음)를보다 쉽게 ​​구현하고 더 안정적이라고 생각합니다!

+0

예. FTP를 사용하여 Android에서 업로드 할 수 있다는 것을 알지 못했습니다. 나는 시도 할 것이다. 조언 해주셔서 감사합니다. – leojg

+0

@leojg 안드로이드에 직접 FTP API가 없다고 잘못 생각하지는 않지만 아파치를 사용할 수는 있습니다. 그것은 잘 작동합니다. 참조 : http://stackoverflow.com/questions/1567601/android-ftp-library – aandroidtest

관련 문제