上传图像文件可以在模拟器上运行,但不能在设备上运行

时间:2015-11-21 09:26:46

标签: php android android-asynctask

我正在尝试将图片文件上传到服务器,这在我尝试使用模拟器时工作正常但从设备上传时给出内部服务器错误

我关注的步骤是:
1]从相机捕获图像并将其存储在外部存储器中 2]在imageview上显示文件 3]按钮单击将文件从外部存储器上传到服务器。

点击上传按钮后,我编写了代码。

Category=(String) category.getSelectedItem();
Bitmap sendbitmap = rotateBitmapImage(BitmapFactory.decodeFile(mCurrentPhotoPath));

ByteArrayOutputStream stream = new ByteArrayOutputStream();
sendbitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
 //compress to which format you want.

 byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);

final ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
nameValuePairs.add(new BasicNameValuePair("userid",Integer.toString(userid)));
nameValuePairs.add(new BasicNameValuePair("State",State));
nameValuePairs.add(new BasicNameValuePair("rc",rc));
nameValuePairs.add(new BasicNameValuePair("vill",vill));
nameValuePairs.add(new BasicNameValuePair("Category",Category));           
new UploadData().execute(nameValuePairs);

UploadData AsyncClass:

private class UploadData extends AsyncTask<ArrayList<NameValuePair>, Void, Void> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(FinalStage.this);
                pDialog.setMessage("Uploading data");
                pDialog.setCancelable(false);
                pDialog.show();
            }

            @Override
            protected Void doInBackground(ArrayList<NameValuePair>... arg0) {

                try{
                    HttpClient httpclient = new DefaultHttpClient();
                   HttpPost("http://xxx.xxx.com/webServices/upload_image.php");
                    httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    final String response = httpclient.execute(httppost,responseHandler);
                    System.out.println("response "+response);
                    JSONArray jlogin = new JSONArray(response);                        
                     JSONObject loginObj = (JSONObject) jlogin.getJSONObject(0);
                     if(loginObj.getString("status").equals("true"))
                     {
                         runOnUiThread(new Runnable() {


                               @Override
                               public void run() {
                                 File f=new File(mCurrentPhotoPath);
                                     f.delete();
                                     img.setImageResource(R.drawable.ic_launcher);
                                   Toast.makeText(FinalStage.this, "Uploaded Successfully ", Toast.LENGTH_LONG).show();                          
                               }
                           });
                     }
                     else
                     {
                         runOnUiThread(new Runnable() {


                               @Override
                               public void run() {
                                   Toast.makeText(FinalStage.this, " Problem upload Uploaded", Toast.LENGTH_LONG).show();                          
                               }
                           });

                     }


                }catch(final Exception e){
                     runOnUiThread(new Runnable() {

                       @Override
                       public void run() {
                           System.out.println("Soham "+e.getMessage());
                           Toast.makeText(FinalStage.this, e.getMessage(), Toast.LENGTH_LONG).show();                              
                       }
                   });

                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                if (pDialog.isShowing())
                    pDialog.dismiss();

            }

        }

Php脚本:

include_once("connection.php");
    $base=$_REQUEST['image'];
    $userid=$_REQUEST['userid'];
    $state=$_REQUEST['State'];
    $rc=$_REQUEST['rc'];
    $vill=$_REQUEST['vill'];
    $Category=$_REQUEST['Category'];

    $date_dir=date("Y-m-d");
    $time_offset="525";
    $time_a=($time_offset * 120);
    $system_time=date('h-i-s',time() + $time_a);

    $querymax="select IFNULL(MAX(id),0)+1 as id from record";
    $stmt = $con->prepare($querymax);
    $stmt->execute();
    $row=$stmt->fetch(PDO::FETCH_ASSOC);
    $id=$row['id'];
    //echo $id;

    $imagename=$state."_".$vill."_".$Category."_".$id.".jpg";

    //$date_dir="12-12-2014";
    //$area_dir="sambhaji";
    //$dirname="uploads/";
    $binary=base64_decode($base);
    header('Content-Type: bitmap; charset=utf-8');


    //$w=mysql_query("INSERT into image values('$login_id','$name',10)");
    $url="webServices/uploads";

    chdir("uploads");
    if(!file_exists($date_dir))
    {
        mkdir($date_dir);
        chdir($date_dir);
        if(!file_exists($state))
        {
            mkdir($state);
            chdir($state);
            if(!file_exists($Category))
            {
                mkdir($Category);
                chdir($Category);

                $file = fopen($imagename, 'wb');
                fwrite($file, $binary);
                fclose($file);

                $path="$url/$date_dir/$state/$Category/";

                $query="insert into record (state,cycle_rout,village,category,image_name,userid,date)values(:state,:rc,:vill,:Category,:imagename,:userid,:date_dir)";
                $stmt = $con->prepare($query);
                $stmt->bindParam(':state',$state);
                $stmt->bindParam(':rc',$rc);
                $stmt->bindParam(':vill',$vill);
                $stmt->bindParam(':Category',$Category);
                $stmt->bindParam(':imagename',$imagename);
                $stmt->bindParam(':userid',$userid);
                $stmt->bindParam(':date_dir',$date_dir);

                if($stmt->execute())
                {
                    header('Content-Type: application/json');
                    $json_output[]=array('status'=>'true');
                    print(json_encode($json_output));
                }
                else
                {
                    header('Content-Type: application/json');
                    $json_output[]=array('status'=>'false');
                    print(json_encode($json_output));
                }
            }
            else
            {   
                chdir($Category);

                $file = fopen($imagename, 'wb');
                fwrite($file, $binary);
                fclose($file);

                $path="$url/$date_dir/$state/$Category/";

                $query="insert into record (state,cycle_rout,village,category,image_name,userid,date)values(:state,:rc,:vill,:Category,:imagename,:userid,:date_dir)";
                $stmt = $con->prepare($query);
                $stmt->bindParam(':state',$state);
                $stmt->bindParam(':rc',$rc);
                $stmt->bindParam(':vill',$vill);
                $stmt->bindParam(':Category',$Category);
                $stmt->bindParam(':imagename',$imagename);
                $stmt->bindParam(':userid',$userid);
                $stmt->bindParam(':date_dir',$date_dir);
                if($stmt->execute())
                {
                    header('Content-Type: application/json');
                    $json_output[]=array('status'=>'true');
                    print(json_encode($json_output));
                }
                else
                {
                    header('Content-Type: application/json');
                    $json_output[]=array('status'=>'false');
                    print(json_encode($json_output));
                }

            }           
        }
        else
        {
            chdir($state);
            if(!file_exists($Category))
            {
                mkdir($Category);
                chdir($Category);

                $file = fopen($imagename, 'wb');
                fwrite($file, $binary);
                fclose($file);

                $path="$url/$date_dir/$state/$Category/";

                $query="insert into record (state,cycle_rout,village,category,image_name,userid,date)values(:state,:rc,:vill,:Category,:imagename,:userid,:date_dir)";
                $stmt = $con->prepare($query);
                $stmt->bindParam(':state',$state);
                $stmt->bindParam(':rc',$rc);
                $stmt->bindParam(':vill',$vill);
                $stmt->bindParam(':Category',$Category);
                $stmt->bindParam(':imagename',$imagename);
                $stmt->bindParam(':userid',$userid);
                $stmt->bindParam(':date_dir',$date_dir);
                if($stmt->execute())
                {
                    header('Content-Type: application/json');
                    $json_output[]=array('status'=>'true');
                    print(json_encode($json_output));
                }
                else
                {
                    header('Content-Type: application/json');
                    $json_output[]=array('status'=>'false');
                    print(json_encode($json_output));
                }
            }
            else
            {   
                chdir($Category);

                $file = fopen($imagename, 'wb');
                fwrite($file, $binary);
                fclose($file);

                $path="$url/$date_dir/$state/$Category/";

                $query="insert into record (state,cycle_rout,village,category,image_name,userid,date)values(:state,:rc,:vill,:Category,:imagename,:userid,:date_dir)";
                $stmt = $con->prepare($query);
                $stmt->bindParam(':state',$state);
                $stmt->bindParam(':rc',$rc);
                $stmt->bindParam(':vill',$vill);
                $stmt->bindParam(':Category',$Category);
                $stmt->bindParam(':imagename',$imagename);
                $stmt->bindParam(':userid',$userid);
                $stmt->bindParam(':date_dir',$date_dir);
                if($stmt->execute())
                {
                    header('Content-Type: application/json');
                    $json_output[]=array('status'=>'true');
                    print(json_encode($json_output));
                }
                else
                {
                    header('Content-Type: application/json');
                    $json_output[]=array('status'=>'false');
                    print(json_encode($json_output));
                }

            }   
        }
    }

为什么会这样?在模拟器上它工作得非常好,但在设备上它给出了问题。它停留在进度条上,并在2分钟后显示Toast消息为内部服务器错误

1 个答案:

答案 0 :(得分:0)

实际上问题在于使用base64编码来传输高质量的图像。我试图上传来自相机的原始图像。我用MultipartEntity替换了base64编码传输。