2013-02-13 96 views
4

我在這個問題上花了2周的時間。我寫了下面的代碼(Android和PHP)。它看起來好,但不工作或工作不正常。客戶端Android似乎發送了一些東西服務器端收到的東西,但我不知道它是什麼。Android:使用php腳本將圖像上傳到遠程MySql數據庫

下面的客戶端Android和服務器上的代碼。

謝謝。

… 
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues()); 
uri_Target=uriTarget.toString(); 
OutputStream imageFileOS; 
try 
{ 
imageFileOS = getContentResolver().openOutputStream(uriTarget); 
imageFileOS.write(arg0); 
imageFileOS.flush(); 
imageFileOS.close(); 

Toast.makeText(ActSismicoCamera_New.this, "Image saved: " + uriTarget.toString(),Toast.LENGTH_LONG).show(); 
SharedPreferences preferences = getPreferences(MODE_PRIVATE); 
SharedPreferences.Editor editor = preferences.edit(); 
editor.putString("percorso",uri_Target);    
editor.commit(); 
inviaPosizione(uri_Target); 
} 
catch (FileNotFoundException e) 
{   
e.printStackTrace(); 
} 
catch (IOException e) 
{   
e.printStackTrace(); 
} 
camera.startPreview(); 
} 
… 
-------------------------------------------------------------------------------------- 
private void inviaPosizione(String percorso) 
{ 
InputStream is=null; 
try 
{ 
String uri_Target; 
SharedPreferences preferences = getPreferences(MODE_PRIVATE); 
uri_Target = preferences.getString("percorso", null);   
Uri imageUri = Uri.parse(uri_Target);   
String filenamelastPhoto; 
filenamelastPhoto = getLastImage(imageUri);   
File sdCard = Environment.getExternalStorageDirectory(); 
File directory = new File (sdCard.getAbsolutePath()+ "/DCIM/Camera/"); 
File immagine = new File(directory, filenamelastPhoto); //or any other format supported 
if(immagine.exists()) 
{ 
Toast.makeText(ActSismicoCamera_New.this, "ESISTE = "+immagine, Toast.LENGTH_LONG).show();   
} 
Bitmap bitmapOrg = BitmapFactory.decodeFile(immagine.toString()); 
    ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
try 
{     
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 60, bao);    
    byte [] ba = bao.toByteArray(); 
    Toast.makeText(ActSismicoCamera_New.this, "inviaPosizione Valore ba= " + ba, Toast.LENGTH_LONG).show(); 
    int flag = 1; 
    String ba1 = Base64.encodeBytes(ba,flag); 
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("tag","registra")); 
    nameValuePairs.add(new BasicNameValuePair("media",ba1)); 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 
    HttpClient httpclient = new DefaultHttpClient(); 
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Custom user agent"); 
    HttpPost httppost = new 
    HttpPost("http://xxxxx.org/AndActSismicoUploadFile.php"); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       is = entity.getContent(); 
      } 
      catch(Exception e) 
      { 
       Toast.makeText(ActSismicoCamera_New.this, "inviaPosizione Exception su HttpClient: " + e.toString(), Toast.LENGTH_LONG).show(); 
      } 
      try 
      { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) 
     { 
     sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString();       
    } 
      catch (Exception e) 
    { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    } 
    catch (Exception e) 
{   
     e.printStackTrace(); 
}    
} 

PHP腳本

<?php  
require_once 'DB_Funzioni.php'; 
if (isset($_POST['tag']) && $_POST['tag'] != '') 
{ 
$tag = $_POST['tag']; 
$oggetto = $_POST['media']; 

if (isset($_POST['media'])) 
    { 
    header('Content-Type: bitmap;charset-utf-8');      
if(move_uploaded_file($_FILES["media"]["tmp_name"],"immagini/" . $_FILES["media"]["name"])) 
    { 
     echo "The file ". $_FILES['media']['name']." has been uploaded"; 
     $info="The file ". basename($_FILES['media']['name'])." has been uploaded"; 
     mail ($destinatario, $ogg, $info); 
    } 
    else 
    { 
     $info="Problema!"; 
     mail ($destinatario, $ogg, $info); 
     switch ($_FILES['media']['error']) 
     { 
        case 1: 
     echo "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
     $info="The uploaded file exceeds the upload_max_filesize directive in php.ini!"; 
     mail ($destinatario, $ogg, $info); 
     break; 
     case 2: 
     echo "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
     $info="The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form!"; 
     mail ($destinatario, $ogg, $info); 
     break; 
     case 3: 
     echo "Only part of the file was uploaded";      
     $info="Only part of the file was uploaded!"; 
     mail ($destinatario, $ogg, $info); 
     break; 
     case 4: 
     echo "No file was uploaded"; 
     $info="No file was uploaded!"; 
     mail ($destinatario, $ogg, $info); 
     break;    
     case 6: 
     echo "Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3"; 
     $info="Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3!"; 
     mail ($destinatario, $ogg, $info); 
     break; 
     case 7: 
     echo "Failed to write file to disk. Introduced in PHP 5.1.0"; 
     $info="Failed to write file to disk. Introduced in PHP 5.1.0!"; 
     mail ($destinatario, $ogg, $info); 
     break; 
     case 8: 
     echo "A PHP extension stopped the file upload"; 
     $info="A PHP extension stopped the file upload!"; 
     mail ($destinatario, $ogg, $info); 
     break;      
     } 
    } 

    $response = array("tag" => $tag, "success" => 0, "error" => 0); 
     $db = new DB_Functions();  
    $fileName = $_FILES['media']['name']; 
    $tmpName = $_FILES['media']['tmp_name']; 
    $fileSize = $_FILES['media']['size']; 
    $fileType = $_FILES['media']['type'];  
    $fp  = fopen($tmpName, 'r'); 
    $content = fread($fp, filesize($tmpName)); 
    $content = addslashes($content); 
    move_uploaded_file($_FILES["media"]["tmp_name"],"immagini/" . $_FILES["media"]["name"]); 
    fclose($fp); 

    if(!get_magic_quotes_gpc()) 
    { 
     $fileName = addslashes($fileName); 
    }  
    $file = $db->storeFile($fileName); 
    if ($file) 
    { 
     $response["success"] = 1; 
     //$response["filename"]["id"] = $file["filename"]; 
     $response["filename"]= $tmpName ; 
     echo json_encode($response); 
      } 
    Else 
    { 
       // user failed to store 
       $response["error"] = 1; 
       //$response["error_msg"] = "Error occured in Insert"; 
       $response["error_msg"] = mysql_error(); 
       echo json_encode($response); 
     } 
    } 
    Else 
    { 
       $response = array("tag" => $tag, "success" => 0, "error" => 0);     
       $response["error"] = 1; 
       $response["error_msg"] = "Media vuoto";     
       echo json_encode($response); 
     }    
} 
//mysql_close(); 
?> 
+1

總是很高興看到非練習五可讀的名字......這使得閱讀代碼變得如此美妙簡單易懂... – WarrenFaith 2013-02-13 10:44:10

+0

爲什麼不把它轉儲到任何它正在獲取的位置,或者可能是SERVER變量下載到文件進行調試? – 2013-02-13 11:32:54

+0

我使用外部服務提供商。我怎樣才能做到這一點 ? – 2013-02-13 12:36:15

回答

0

這不是一個完整的答案......因爲我們去,我會完成這個答案...

首先,我會建議你檢查,如果你是獲取你應該得到的發佈數據。請後的頂部插入此:

if (isset($_POST['tag']) && $_POST['tag'] != '') 
{ 

...

file_put_contents ("mydebugdata.txt",json_encode($_POST)); 

這應該轉儲腳本recieving到文件 「mydebugdata.txt」 ...... json_encode的數據()提供在$ _ POST一些結構......這樣你就可以讀取數據...

然後嘗試保存圖片,並張貼在這裏mydebugdata.txt的內容...

相關問題