【问题标题】:JSON and upload image to serverJSON 并将图像上传到服务器
【发布时间】:2011-11-18 00:10:13
【问题描述】:

我想将图像从 android 上传到我的 sql 数据库,我有这样的代码:

private void uploadFile() {
    // TODO Auto-generated method stub
    Bitmap bitmapOrg= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() +"/Chart1.png");
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte [] ba = bao.toByteArray();
    String ba1=Base64.encodeBytes(ba);
    ArrayList nameValuePairs = new
    ArrayList();
    nameValuePairs.add(new BasicNameValuePair("image",ba1));
    try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new
    HttpPost("http://ipadress/base.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    }catch(Exception e){
    Log.e("log_tag", "Error in http connection "+e.toString());
    }
}

但同时我也想将我的用户名上传到我的数据库(假设我使用 edittext 检索用户名),有人知道该怎么做吗?我应该添加什么样的代码?谢谢之前

我在数据库中的表应该是这样的:

ID |用户名 |文件 |

我可以用来上传字符串数据的 JSON 代码是这样的:

 private void uploadFile() {
    // TODO Auto-generated method stub
    String nama = getIntent().getStringExtra("user");
    Bitmap bitmapOrg= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() +"/Chart1.png");
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte [] ba = bao.toByteArray();
    String ba1=Base64.encodeBytes(ba);
    ArrayList nameValuePairs = new ArrayList();
    nameValuePairs.add(new BasicNameValuePair("image",ba1));
    nameValuePairs.add(new BasicNameValuePair("username",nama));
    try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new
    HttpPost("http://139.195.144.67/BloodGlucose/base2.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse httpRespose = httpclient.execute(httppost);
   HttpEntity httpEntity = httpRespose.getEntity();
   InputStream in = httpEntity.getContent();
   BufferedReader read = new BufferedReader(new InputStreamReader(in));

   String isi= "";
   String baris= "";

   while((baris = read.readLine())!=null){
      isi+= baris;
   }

       //Jika isi tidak sama dengan "null " maka akan tampil Toast "Register Success" sebaliknya akan tampil "Register Failure"
       if(!isi.equals("null")){                  
           Toast.makeText(this, "Register Success", Toast.LENGTH_LONG).show();
       }else{
           Toast.makeText(this, "Register Failure", Toast.LENGTH_LONG).show();
       }

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

我可以合并这些代码吗?还是有另一种方法可以同时从android上传文件和字符串?谢谢之前

我的 php 代码:

<?php
include_once("koneksi.php");

$username = $_REQUEST['username'];

$hasil = mysql_query("select (max(ID)+1)as newid  from userownfile"); 
$row = mysql_fetch_row($hasil); 

$base = $_REQUEST['image'];
$filename = $row[0] . ".jpg";
$buffer=base64_decode($base);
$path = "img/".$filename.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $buffer);
fclose($handle);
$conn=mysql_connect("localhost","root","");
mysql_select_db("db_bloodglucose");


$sql = "insert into userownfile(username,file) values('$username','" . $path . "')";
mysql_query($sql);


$string= "select * from userownfile";
$my_string= mysql_query($string);
if($my_string){
   while($object= mysql_fetch_assoc($my_string)){
      $output[] = $object;
   }

   echo json_encode($output);

?>

【问题讨论】:

    标签: php android mysql database json


    【解决方案1】:

    是的,您可以而且应该尽量减少对服务器的调用次数。只需使用适当的数据向您的nameValuePairs 添加另一个参数。

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

    这很简单。您应该真正关注的是服务器端代码,因为它需要能够处理不同的数据。

    【讨论】:

    • 所以我只需要使用我的 JSON 代码,不是吗?我一直在添加我的 php 代码。这是正确的?如果不正确,我应该输入什么样的代码?谢谢之前
    • 我不是 PHP 专家,但看起来您的想法是正确的(从 POST 对象中获取正确的参数)。
    • 我已经编辑了我的 JSON 代码,是这样吗?谢谢之前
    【解决方案2】:

    在我的方法中,我使用了 org.apache.http.entity.mime.MultipartEntity 并将图像文件名添加为 FileBody

    entity.addPart("image_" + photo_count, new FileBody(
                            new File(failed.getFilenames()[i])));
    

    然后将 MultiPartEntity 传递给 HttpPost。我没有发布完整的代码,因为它有大量与您的问题无关的 cmets 和代码。通过将图像作为 FileBody 传递,可以使用标准 php 文件处理代码(见下文)获取图像。

      if ((!empty($_FILES[$im])) && ($_FILES[$im]['error'] == 0)) {
                  $newname = dirname(__FILE__) . '/../photo/' . $campaign . '/' . $fn;
                  if (!file_exists($newname)) {
                      if (move_uploaded_file($_FILES[$im]['tmp_name'], $newname)) {
                          //$resp = "The file " . $fn . " has been uploaded";
                          //printf("%s", $resp);
                      } else {
                        $error = $error + 1;      
                      } 
                  }else{
                    //image file already exists
                    $error = $error + 1;
                  }
              } else {
                  $error = $error +1;
              }
    

    出于我的目的,上面的代码在我处理多个图像时处于循环中

    $im = 'image_' . $i;
    

    指实体中图片的名称。

    对不起,我赶时间。

    忘记提及我没有使用 Base64 字符串方法的原因是它限制了您可以发送的图像的大小。实体中的 FileBody 方法是我发现的最佳方法。

    您可以使用以下方式传递字符串:

    entity.addPart("address", new StringBody(failed[0].getAddress()));
    
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 20000); // Timeout
    
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("address", new StringBody("my address example"));
    entity.addPart("image_0", new FileBody(new File("filename of image")));
    
    HttpPost post = new HttpPost("server address");
    post.setEntity(entity);
    
    HttpResponse response  = client.execute(post);
    

    【讨论】:

    • 我以前从来没有用过这个,所以我不知道怎么做,你能给我一个完整的例子吗?谢谢之前
    • 我已经编辑了答案,向您展示如何将 HttpPost 与 MultiPartEntity 一起使用。从这里获取 jar 文件 docjar.com/jar_detail/httpmime-4.0.1.jar.html
    • @Bear 我很好奇 Base64 图像大小限制。为什么会有一个?
    • 我认为不会有,但是当我尝试使用这种方法 (blog.sptechnolab.com/2011/03/09/android/…) 将图像作为 Base64 字符串发送时,如果图像超过 512kb,我会遇到很多问题。
    猜你喜欢
    • 2015-03-02
    • 2022-09-26
    • 2017-06-22
    • 2013-12-17
    • 2014-03-21
    • 2017-05-31
    • 2013-11-02
    • 2014-03-24
    • 1970-01-01
    相关资源
    最近更新 更多