2014-12-26 4 views
0

안드로이드 앱에서 php/mysql을 실행하는 서버로 이미지를 업로드하려고합니다. 이것은 처음의 두 로그 함수는 제 로그 관련이없는안드로이드에서 서버로 이미지 업로드가 작동하지 않습니다.

./../../pics/species/22/39.png 
/tmp/php9YSsDz 

생산

<?php 

    if (isset($_FILES['uploadedfile']) && 
     isset($_GET['user_id']) && 
     isset($_GET['fish_id']) && 
     isset($_GET['is_node']) && 
     isset($_GET['comment']) && 
     isset($_GET['lat']) && 
     isset($_GET['long']) && 
     isset($_GET['addr'])) { 

     $user_id = $_GET['user_id']; 
     $fish_id = $_GET['fish_id']; 
     $is_node = $_GET['is_node']; 
     $comment = mysql_real_escape_string($_GET['comment']); 
     $lat = $_GET['lat']; 
     $long = $_GET['long']; 
     $addr = mysql_real_escape_string($_GET['addr']); 

     if ($is_node=="1") { 
      $table = "category"; 
     } else { 
      $table = "species"; 
     } 

     // add the fish image to the table 
     $query = "INSERT INTO {$table}_images ({$table}_id,comment,approved,main,date_added,user_id) VALUES ({$fish_id},'{$comment}',1,0,NOW(),{$user_id})"; 
     mysql_query($query);  
     $pic_id = mysql_insert_id(); 


     $filename = $pic_id . '.png'; 
     $target_path = "./../../pics/{$table}/{$fish_id}/"; 


     // make the directory is not exist 
     if (!is_dir($target_path)) { 
      $old_umask = umask(0); 
      mkdir($target_path, 0777); 
      umask($old_umask);   
     } 

     // move the image there 
     if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path . $filename)) { 
      $errorMessage = $GLOBALS['UPLOAD_IMAGE_ERROR']; 

      logQuery($target_path . $filename); 
      logQuery($_FILES['uploadedfile']['tmp_name']); 
      logQuery($errorMessage); 

     } else { 

      $location_id = 0; 
      if ($is_node != "1" && $addr != "") { 
       // create the new location 
       $query = "INSERT INTO location (species_id, address, latitude, longitude, comment, approved) VALUES ({$fish_id}, '{$addr}', {$lat}, {$long}, '', 1)"; 

       mysql_query($query); 
       if (mysql_error() == "") { 
        $location_id = mysql_insert_id(); 
       } 
      } 

      $successMessage = array(
       'pic_id' => $pic_id, 
       'elink' => getExternalLink($table, $fish_id, $pic_id), 
       'locationId' => $location_id 
      ); 
     } 
    } else { 
     $errorMessage = $GLOBALS['MISSING_INFO']; 
    } 

?> 

안드로이드 코드

private static String UploadImageHelper(Context context, Bitmap bitmap, String url) throws ClientProtocolException, IOException { 
    if (bitmap != null) { 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     bitmap.compress(CompressFormat.PNG, 100, bos); 
     byte[] data = bos.toByteArray(); 
     String fileName = "image"; 
     ByteArrayBody bab = new ByteArrayBody(data, fileName); 

     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
     reqEntity.addPart("uploadedfile", bab); 

     Pair<String, Integer> pair = httpRequestHelper(url, reqEntity); 
     return pair.first; 
    } 
    return null; 
} 

private static Pair<String, Integer> httpRequestHelper(String url, HttpEntity reqEntity) { 
    try { 
     HttpParams httpParameters = new BasicHttpParams(); 
     int timeoutConnection = TIMEOUT_SECONDS * 1000; 
     HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
     int timeoutSocket = TIMEOUT_SECONDS * 1000; 
     HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

     HttpPost httppost = new HttpPost(url); 
     httppost.setEntity(reqEntity); 

     HttpClient client = new DefaultHttpClient(httpParameters); 
     HttpResponse entity = client.execute(httppost); 
     int responseCode = entity.getStatusLine().getStatusCode(); 

     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     entity.getEntity().writeTo(baos); 
     byte[] content = baos.toByteArray(); 
     String responseVal = Common.unzipString(content); 

     //Log.d("IMAGE SAVE", responseVal); 

     return new Pair<String, Integer>(responseVal, responseCode); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return getErrorReturn(); 
} 

PHP이다. 그것은 단지 내 자신의 사용자 정의 오류 메시지입니다.

누구도 move_uploaded_file 함수가 실패하는 이유를 알고 있습니까?

감사

+0

'$ _FILES [ 'uploadedfile'] [ '오류']'대신'의 $ GLOBALS [ 'UPLOAD_IMAGE_ERROR']에 오류가 시도' – waki

+0

그것을 그것에 대해 '0'이 인쇄되었습니다. – omega

+0

'http : // php.net/manual/ko/features.file-upload.errors.php''오류 메시지 설명' – waki

답변

1

사용이 코드 :

public void upload_file(String single_img) { 
    HttpURLConnection connection = null; 
    DataOutputStream outputStream = null; 
    DataInputStream inputStream = null; 

    String pathToOurFile = single_img; 
    Log.i("path of image in upload file mathod:", pathToOurFile); 
    String urlServer = IMAGE_URL; 
    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 

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

    try { 

     // for reducing the height and width of the image 
     Bitmap bitmap = ShrinkBitmap(pathToOurFile, 128, 128); 

     File file = new File(pathToOurFile); 
     FileOutputStream fOut = new FileOutputStream(file); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut); 
     fOut.flush(); 
     fOut.close(); 

     FileInputStream fileInputStream = new FileInputStream(file); 

     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); 

     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(); 

     fileInputStream.close(); 
     outputStream.flush(); 
     outputStream.close(); 
    } catch (Exception ex) { 
     // Exception handling 
    } 
} 
관련 문제