发布的base64图像到PHP服务器的android [英] Posting base64 image to php server in android

查看:182
本文介绍了发布的base64图像到PHP服务器的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作,其中用户可以将图像上传到服务器的模块上。要做到这一点,我必须要改变所选图像为Base64的。转换后,我不得不使用JSON的POST方法来上传图片,但每次应用程序崩溃和放弃的logcat此错误

错误转换结果显示java.lang.NullPointerException:锁== NULL

和错误的另一条线是

错误解析数据org.json.JSONException:输入结束的字符0

这是我的code,我想,请看看,让我有什么错,我在这里做什么。

  buttonLoadPicture.setOnClickListener(新View.OnClickListener(){

        @覆盖
        公共无效的onClick(视图v){
            // TODO自动生成方法存根

            意图I =新的意图(
                    Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(ⅰ,RESULT_LOAD_IMAGE);
        }
    });

}

@覆盖
保护无效onActivityResult(INT申请code,INT结果code,意图数据){
    super.onActivityResult(要求code,因此code,数据);

    如果(要求code == RESULT_LOAD_IMAGE和放大器;&安培;结果code == RESULT_OK和放大器;&安培;!NULL =数据){
        乌里selectedImage = data.getData();
        的String [] filePathColumn = {MediaStore.Images.Media.DATA};

        光标光标= getContentResolver()查询(selectedImage,
                filePathColumn,NULL,NULL,NULL);
        cursor.moveToFirst();

        INT参数:columnIndex = cursor.getColumnIndex(filePathColumn [0]);
        字符串picturePath = cursor.getString(参数:columnIndex);
        cursor.close();

        ImageView的ImageView的=(ImageView的)findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.de codeFILE(picturePath));

        SS = BitmapFactory.de codeFILE(picturePath);
        Log.d(价值,ss.toString());


        ByteArrayOutputStream BAOS =新ByteArrayOutputStream();
        ss.com preSS(Bitmap.Com pressFormat.JPEG,100,BAOS);
        byte []的B = baos.toByteArray();
        字符串imageEn codeD = Base64.en codeToString(B,Base64.DEFAULT);

        EN codeDIMAGE = imageEn coded.toString();

        Log.e(看,imageEn codeD); // **工作正常**
        Log.e(EN codeDIMAGE,恩codeDIMAGE); // **工作正常**

       新PostImage()执行();

    }
}

类PostImage扩展的AsyncTask<字符串,字符串,字符串> {

    @燮pressWarnings(德precation)
    @覆盖
    保护字符串doInBackground(字符串参数... args){

        // TODO自动生成方法存根

        字符串连接codedString = EN codedImage.toString();

        Log.d(stringgggg,恩codedString); // **工作正常**

     名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();

        params.add(新BasicNameValuePair(uploaded_file,恩codedString));
        字符串URI =htt​​p://192.168.2.166/uploadimage/upload.php;
        JSONObject的JSON = jsonParser.makeHtt prequest(URI,POST,则params);

        Log.d(valueeeeee,json.toString()); // ** Crashhhh !!!!! **
        返回json.toString();
    }
}
 

}

这是我的PHP code

 < PHP

    $ JSON [成功] = 1; $ JSON [信息] =YOU ARE HERE ... upload.php的;

    $ JSON [形象] = $ _ FILES ['uploaded_file'] ['名称'];
    $ JSON ['tmp_name的值'] = $ _ FILES ['uploaded_file'] ['tmp_name的值'];
    回声json_en code($ JSON);

    死();
    //的print_r($ _ FILES);死();
    $ FILE_PATH =上传/;

    $ FILE_PATH = $ FILE_PATH。基本名($ _ FILES ['uploaded_file'] ['名称']);
    如果(move_uploaded_file($ _ FILES ['uploaded_file'] ['tmp_name的值'],$ FILE_PATH)){
        //回声成功;
         $ JSON [成功] = 1; $ JSON [信息] =成功后救;
    } 其他{
       //回声不及格;
         $ JSON [成功] = 0; $ JSON [信息] =失败后保存;
    }

    //的print_r($ JSON);
    //后续代码var_dump(json_en code($ JSON));
    回声json_en code($ JSON);
?>
 

解决方案

我检查你的错误线

 的JSONObject JSON = jsonParser.makeHtt prequest(URI,POST,则params);
 

但无法找到 makeHtt prequest 此Method.so给你下面的链接, 确保你成功响应,然后你去<$​​ C $ C>的JSONObject 解析。

请检查链接1 < A HREF =htt​​p://loopj.com/android-async-http/相对=nofollow>喜欢下载jar文件异步HTTP客户端并进行API调用>

 公共无效makeHTTPCall(){
        prgDialog.setMessage(调用PHP的);
        RequestParams PARAMS =新RequestParams();
        params.put(钥匙,价值);
        params.put(多,数据);
        AsyncHttpClient客户端=新AsyncHttpClient();
        //不要忘了更改IP地址到你的局域网的地址。端口号为好。
        client.post(http://192.168.2.5:9000/imgupload/upload_image.php
                PARAMS,新AsyncHtt presponseHandler(){
                    //当REST返回的响应具有断点续传
                    //响应code'200'
                    @覆盖
                    公共无效的onSuccess(字符串响应){
                        //隐藏进度对话框
                        prgDialog.hide();
                        Toast.makeText(getApplicationContext(),响应,
                                Toast.LENGTH_LONG).show();
                    }

                    //当REST返回的响应具有断点续传
                    //响应code比'200'等,如404,
                    //'500'或'403'等
                    @覆盖
                    公共无效onFailure(INT状态code,可抛出错误,
                            字符串的内容){
                        //隐藏进度对话框
                        prgDialog.hide();
                        //当HTTP响应code是'404'
                        如果(状态code == 404){
                            Toast.makeText(getApplicationContext(),
                                    请求的资源未找到,
                                    Toast.LENGTH_LONG).show();
                        }
                        //当HTTP响应code是'500'
                        否则,如果(状态code == 500){
                            Toast.makeText(getApplicationContext(),
                                    出事了服务器端
                                    Toast.LENGTH_LONG).show();
                        }
                        //当HTTP响应code比404等,500
                        其他 {
                            Toast.makeText(
                                    getApplicationContext(),
                                    发生错误\ñ最常见的错误:\ n1的设备没有连接到互联网\ N2 Web应用程序不部署在应用服务器\ N3应用程序服务器没有运行\ñHTTP状态code:。
                                            +状态code,Toast.LENGTH_LONG)
                                    。显示();
                        }
                    }
                });
    }
 

I am working on a module in which user can upload the image to the server. To achieve this, I have to change selected image into Base64. After conversion, I have to use Json POST method to upload image, but every time application crashes and Logcat give this error

Error converting result java.lang.NullPointerException: lock == null

and another line of error is

Error parsing data org.json.JSONException: End of input at character 0 of 

this is my code that I am trying, Please have a look and let me what mistake I am doing here.

    buttonLoadPicture.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent i = new Intent(
                    Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        ss = BitmapFactory.decodeFile(picturePath);
        Log.d("value", ss.toString());


        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        ss.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);

        encodedImage = imageEncoded.toString();

        Log.e("LOOK", imageEncoded); // **working proper**
        Log.e("encodedImage", encodedImage);// **working proper**

       new PostImage().execute();

    }
}

class PostImage extends AsyncTask<String, String, String>{

    @SuppressWarnings("deprecation")
    @Override
    protected String doInBackground(String... args) {

        // TODO Auto-generated method stub

        String encodedString = encodedImage.toString();

        Log.d("stringgggg", encodedString);//**working proper**

     List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("uploaded_file", encodedString));
        String uri = "http://192.168.2.166/uploadimage/upload.php";         
        JSONObject json = jsonParser.makeHttpRequest(uri,"POST",params);

        Log.d("valueeeeee", json.toString());// **Crashhhh!!!!!**
        return json.toString();
    }
}

}

this is my php code

<?php

    $json["success"] = 1; $json["message"] = "YOU ARE HERE... UPLOAD.PHP";

    $json['image']=$_FILES['uploaded_file']['name'];
    $json['tmp_name']=$_FILES['uploaded_file']['tmp_name'];
    echo json_encode($json);

    die();
    //print_r($_FILES); die();
    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        //echo "success";
         $json["success"] = 1; $json["message"] = "Successfully post save"; 
    } else{
       // echo "fail";
         $json["success"] = 0; $json["message"] = "Fail post save"; 
    }

    // print_r($json);
    // var_dump(json_encode($json));
    echo json_encode($json);
?>

解决方案

I checked your error line at

JSONObject json = jsonParser.makeHttpRequest(uri,"POST",params);

but could not found makeHttpRequest this Method.so giving you below link, Make sure you get Success response and then you go for JSONObject parsing.

Please check Link 1 Link2 download jar file Asynchronous Http Client and make Api call like

public void makeHTTPCall() {
        prgDialog.setMessage("Invoking Php");       
        RequestParams params = new RequestParams();
        params.put("key", "value");
        params.put("more", "data");
        AsyncHttpClient client = new AsyncHttpClient();
        // Don't forget to change the IP address to your LAN address. Port no as well.
        client.post("http://192.168.2.5:9000/imgupload/upload_image.php",
                params, new AsyncHttpResponseHandler() {
                    // When the response returned by REST has Http
                    // response code '200'
                    @Override
                    public void onSuccess(String response) {
                        // Hide Progress Dialog
                        prgDialog.hide();
                        Toast.makeText(getApplicationContext(), response,
                                Toast.LENGTH_LONG).show();
                    }

                    // When the response returned by REST has Http
                    // response code other than '200' such as '404',
                    // '500' or '403' etc
                    @Override
                    public void onFailure(int statusCode, Throwable error,
                            String content) {
                        // Hide Progress Dialog
                        prgDialog.hide();
                        // When Http response code is '404'
                        if (statusCode == 404) {
                            Toast.makeText(getApplicationContext(),
                                    "Requested resource not found",
                                    Toast.LENGTH_LONG).show();
                        }
                        // When Http response code is '500'
                        else if (statusCode == 500) {
                            Toast.makeText(getApplicationContext(),
                                    "Something went wrong at server end",
                                    Toast.LENGTH_LONG).show();
                        }
                        // When Http response code other than 404, 500
                        else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
                                            + statusCode, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                });
    }

这篇关于发布的base64图像到PHP服务器的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆