正在上传图片ANDROID

时间:2012-09-25 08:54:20

标签: php android image

我按照教程如何上传图片,但文件没有出现,我不知道我哪里做错了。基本上,我从手机图库中选择一张照片并发送给它。

以下是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);

    btnUpload = (Button) this.findViewById(R.id.btnUpload);

    btnUpload.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // To open up a gallery browser
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Select Picture"), 1);
        }
    });

    btnSent = (Button) this.findViewById(R.id.btnSent);

    btnSent.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            HttpUploader uploader = new HttpUploader();
            try {
                // String image_name =
                uploader.execute(getRealPathFromURI(currImageURI)).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    });
}

// To handle when an image is selected from the browser
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            // currImageURI is the global variable I’m using to hold the
            // content:
            currImageURI = data.getData();
            path = (TextView) findViewById(R.id.path);
            path.setText(getRealPathFromURI(currImageURI));
        }
    }
}

// Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
    android.database.Cursor cursor = managedQuery(contentUri, proj, // Which
                                                                    // columns
                                                                    // to
                                                                    // return
            null, // WHERE clause; which rows to return (all rows)
            null, // WHERE clause selection arguments (none)
            null); // Order-by clause (ascending by name)
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

这是我的http:

for (String sdPath : path) {
        Bitmap bitmapOrg = BitmapFactory.decodeFile(sdPath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        // Resize the image
        double width = bitmapOrg.getWidth();
        double height = bitmapOrg.getHeight();
        double ratio = 400 / width;
        int newheight = (int) (ratio * height);

        bitmapOrg = Bitmap.createScaledBitmap(bitmapOrg, 400, newheight,
                true);

        // Here you can define .PNG as well
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
        String ba1 = Base64.encodeBytes(ba);

        System.out.println("uploading image now ——–" + ba1);

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("image", ba1));

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://path to my server/upload.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            // print response
            outPut = EntityUtils.toString(entity);
            Log.i("GET RESPONSE—-", outPut);

            // is = entity.getContent();
            Log.e("log_tag ******", "good connection");

            bitmapOrg.recycle();

        } catch (Exception e) {
            Log.e("log_tag ******",
                    "Error in http connection " + e.toString());
        }

这是我的PHP代码:

<?php

$base = $_REQUEST["image"];

if (isset($base)) {

$suffix = createRandomID();
$image_name = "img_".$suffix."_".date("Y-m-d-H-m-s").".jpg";

// base64 encoded utf-8 string
$binary = base64_decode($base);

// binary, utf-8 bytes

header("Content-Type: bitmap; charset=utf-8");

$file = fopen("../images/post_images/" . $image_name, "wb");

fwrite($file, $binary);

fclose($file);

die($image_name);

} else {

die("No POST");
}

function createRandomID() {

$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";
//srand((double) microtime() * 1000000);

$i = 0;

$pass = "";

while ($i <= 5) {

$num = rand() % 33;

$tmp = substr($chars, $num, 1);

$pass = $pass . $tmp;

$i++;
}
return $pass;
}
?>

1 个答案:

答案 0 :(得分:0)

此脚本正常运行,您可以在servar的upload文件夹中找到该图像。

<?php 
 $target = "upload/"; 

 $target = $target . basename( $_FILES['uploaded']['name']) ; 
 $ok=1; 
 if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
 {
     echo "yes";
 } 
 else {
     echo "no";
 }
?> 

查看此answer