将图像从android上传到服务器无法正常工作

时间:2014-12-26 03:11:31

标签: php android mysql image upload

我正在尝试将图像从我的Android应用程序上传到运行php / mysql的服务器。这是android代码

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

<?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'];
    }

?>

前两个日志函数生成

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

第三个日志不相关。这只是我自己的自定义错误消息。

有谁知道move_uploaded_file函数失败的原因?

由于

1 个答案:

答案 0 :(得分: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
    }
}