使用Base64将图像从android上传到服务器

时间:2013-03-19 18:38:08

标签: android base64 image-uploading

我使用Base64类在Android服务器上上传图片。

在服务器端,我有两件事:

- upload.php 脚本和

- test.jpg 图片文件

每次上传完成 test.jpg 都会被新图片覆盖。

如何解决这个问题?

以下是我的上传代码:

InputStream is;
    private void uploadSlike (Bitmap bitmapOrg) {

        try {

            ByteArrayOutputStream bao = new ByteArrayOutputStream();

            bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

            byte [] ba = bao.toByteArray();

            String ba1=Base64.encodeBytes(ba);

            ArrayList<NameValuePair> nameValuePairs = new

            ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("image",ba1));



            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new

            HttpPost("http://myserver/pictureupload.php");

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();

            is = entity.getContent();

            System.out.println(entity.getContentLength());


        } catch (Exception e) {


            System.out.println("Greska prilikom uploada:"+e);
        }

        System.out.println("zavrsni sam uplaod");


                }

upload.php脚本

<?php

$base=$_REQUEST['image'];

echo $base;

// base64 encoded utf-8 string

$binary=base64_decode($base);

// binary, utf-8 bytes

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

// print($binary);

//$theFile = base64_decode($image_data);

$file = fopen('test.jpg', 'wb');

fwrite($file, $binary);

fclose($file);

echo '<img src=test.jpg>';

?>

2 个答案:

答案 0 :(得分:1)

嘿兄弟使用这个上传不同名称的图像

$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
$file = fopen($new_image_name, 'wb');

fwrite($file, $binary);

fclose($file);

答案 1 :(得分:0)

我找到解决方案:

这是修改过的php脚本:

<?php

$base=$_REQUEST['image'];

$ImageName=$_REQUEST['ImageName'];

copy('test.jpg',$ImageName);

echo $base;

// base64 encoded utf-8 string

$binary=base64_decode($base);

// binary, utf-8 bytes

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

// print($binary);

//$theFile = base64_decode($image_data);

$file = fopen($ImageName, 'wb');

fwrite($file, $binary);

fclose($file);

echo '<img src=test.jpg>';

?>

和此:

nameValuePairs.add(new BasicNameValuePair("ImageName","newImage.jpg"));