选择图像并上传到服务器

时间:2014-07-12 15:01:18

标签: java php android image upload

我正在编写一个应用程序,其中一个用户可以上传一个头像。它似乎工作,但最后上传的文件/图像在服务器上是空的。我想这个图像不会在服务器端正确解码。遵循logcat消息:

07-12 16:54:25.809: E/ViewRootImpl(13702): sendUserActionEvent() mView == null
07-12 16:54:26.176: E/JSON(13702): img_xebf47_2014-07-12-16-07-16.jpg
07-12 16:54:26.207: E/JSON Parser(13702): Error parsing data org.json.JSONException: Value img_xebf47_2014-07-12-16-07-16.jpg of type java.lang.String cannot be converted to JSONObject

在Android方面,我有以下课程:

  • UploadAvatarActivity.java - >处理相机意图,显示所选图像,从UserFunctions.java
  • 开始使用调用函数上传
  • UserFunctions.java - >包含上传头像的函数,函数从UploadAvatarActivity.java获取参数,然后创建JSON对象并解析url和参数
  • JSONParser.java - >启动HTTP-Request

UploadAvatarActivity.java中的相关区域:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        switch (requestCode) {

        case PICK_FROM_FILE:
            /**
             * After selecting image from files, save the selected path
             */
            mImageCaptureUri = data.getData();
            imagepath = getPath(mImageCaptureUri);
            Bitmap bitmap2 = BitmapFactory.decodeFile(imagepath);
            mImageView.setImageBitmap(bitmap2);

            NetAsync();

            break;

        }

@Override
        protected JSONObject doInBackground(String... args) {

            UserFunctions userFunction = new UserFunctions();

            ByteArrayOutputStream bao = new ByteArrayOutputStream();

            byte[] ba = bao.toByteArray();
            int flag = 0;
            String krt = Base64.encodeToString(ba, flag);

            JSONObject json = userFunction.uploadAvatar(uid, krt);

            return json;

        }

UserFunctions.java:

public class UserFunctions {

    private JSONParser jsonParser;

    // URL of the PHP API
    private static String upload_avatarURL = "http://xxxxxxxx/xxxAPI/";

    // Tag for serverside
    private static String upload_avatar_tag = "uploadavatar";

    // constructor
    public UserFunctions() {
        jsonParser = new JSONParser();
    }


    /**
     * Function to upload avatar
     **/
    public JSONObject uploadAvatar(String uid, String image) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", upload_avatar_tag));
        params.add(new BasicNameValuePair("uid", uid));
        params.add(new BasicNameValuePair("image", image));

        JSONObject json = jsonParser.getJSONFromUrl(upload_avatarURL, params);
        return json;
    }

}

这里处理HTTp请求的JASONParser:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

最后在服务器端我遵循PHP代码:

if ($tag == 'uploadavatar') {
        $uid = $_POST['uid'];

        $base = $_POST["image"];


            if (isset($base)) {

            $suffix = $db->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");
        }
 }

如果其他人遇到同样的问题:

我通过以下更改修复了我的问题:

@Override
        protected JSONObject doInBackground(String... args) {

            UserFunctions userFunction = new UserFunctions();

// Here I had to compress and encode to string!!
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            String krt = Base64.encodeToString(imageBytes, Base64.DEFAULT);

            JSONObject json = userFunction.uploadAvatar(uid, krt);

            return json;

        }

1 个答案:

答案 0 :(得分:1)

如果其他人有同样的问题:

我通过以下更改修复了我的问题:

@Override
        protected JSONObject doInBackground(String... args) {

            UserFunctions userFunction = new UserFunctions();

// Here I had to compress and encode to string!!
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            String krt = Base64.encodeToString(imageBytes, Base64.DEFAULT);

            JSONObject json = userFunction.uploadAvatar(uid, krt);

            return json;

        }