簡體   English   中英

選擇圖像並上傳到服務器

[英]Select image and upload to Server

我正在編寫一個應用程序,用戶可以在其中上傳頭像。 似乎可行, 但最后在服務器上上傳的文件/圖像為空。 我想圖像將無法在服務器端正確解碼。 以下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請求

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;

        }

如果其他人有相同的問題:

我通過以下更改解決了我的問題:

@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;

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM