图片上传的片段代码无效

时间:2016-06-13 06:57:42

标签: android

通常我有Image picker的代码,我在片段中有以下代码但是每当我运行数据时都会发送到服务器但是不会发送图像。

    private void startingCameraIntent() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, CAMERA_PIC_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("====onActivityResult");
        if (requestCode == SELECT_PICTURE && resultCode == getActivity().RESULT_OK) {


            selectedImageUri = data.getData();
            String[] projection = {MediaStore.MediaColumns.DATA};
            CursorLoader cursorLoader = new CursorLoader(getActivity(), selectedImageUri, projection, null, null,
                    null);
            Cursor cursor = cursorLoader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            cursor.moveToFirst();
            filepath = cursor.getString(column_index);

            System.out.println("file path is :----" + filepath);
            System.out.println("file selectedImageUri :----" + selectedImageUri);

            imageview_pic.setVisibility(View.VISIBLE);
            Picasso.with(getActivity()).load(selectedImageUri).fit().into(imageview_pic);

        } else if (requestCode == CAMERA_PIC_REQUEST && resultCode == getActivity().RESULT_OK) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.PNG, 100, bytes);
            // thumbnail.createScaledBitmap(thumbnail,1024,768,true);

            File destination = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // ivImage.setImageBitmap(thumbnail);
            imageview_pic.setVisibility(View.VISIBLE);
            System.out.println("===Image Path : " + destination);
            System.out.println("===thumbnail : " + thumbnail);
            filepath = String.valueOf(destination);
            Log.d("Image path",filepath);
            imageview_pic.setImageBitmap(thumbnail);
        } else {

        }

    }

    //----------------------------------------------------------------------------------------------------------
    class postadd extends AsyncTask<String, String, JSONObject>
    {

        String title = ettitle.getText().toString();
        String name = etname.getText().toString();
        String city = etcity.getText().toString();
        String district = text.getText().toString();
        String taluka = text1.getText().toString();
        String contact = etcontact.getText().toString();
        String price = etprice.getText().toString() + " / " + item;
        String details = etdetails.getText().toString();
       // String img=selectedImageUri.getPath().toString();


        JSONParser jsonParser = new JSONParser();

        private static final String LOGIN_URL = "Image Upload URL";

        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "result";


        @Override
        protected void onPreExecute() {

            pd.show();
        }

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

            try {

                HashMap<String, String> map = new HashMap<>();
                map.put("file_upload",filepath);
                map.put("add_title", title);
                map.put("cat", cat_id);
                map.put("sub_cat", finalsubcatid);
                map.put("add_price", price);
                map.put("add_description", details);
                map.put("add_name", name);
                map.put("add_phone", contact);
                map.put("add_city", city);
                map.put("add_district", district);
                map.put("add_taluka", taluka);

                Log.d("request", "starting");

                JSONObject json = jsonParser.makeHttpRequest(
                        LOGIN_URL, "POST", map);

                if (json != null) {
                    Log.d("JSON result", json.toString());

                    return json;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(JSONObject json) {

            if (pd != null && pd.isShowing())
            {
                pd.dismiss();
            }

            if (json != null) {
               /* Toast.makeText(SignUp.this, json.toString(),
                        Toast.LENGTH_LONG).show();
*/
                try {
                    //  result = json.getInt(TAG_SUCCESS);
                    result = json.getString(TAG_MESSAGE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if(result.equals("true"))
            {

                Toast.makeText(getActivity(),"Add Posted Successfull",Toast.LENGTH_SHORT).show();

            }


            else
            {
                Toast.makeText(getActivity(),"Post  Not Done...",Toast.LENGTH_SHORT).show();

            }
        }
    }

以上代码用于PostAddFragment,其中Camera intent被调用click,当点击添加按钮时,它将图像上传到服务器。

1 个答案:

答案 0 :(得分:1)

您不能发送这样的图像,您可能需要将其作为Multipart Entity发送,或者您也可以使用Base64编码将其作为字符串发送,这可能是忙乱的。

    String path = Utils.getPath(getApplicationContext(), uri);
    Bitmap bitmap = BitmapFactory.decodeFile(path);
    byte[] imageBytes = getBytesFromBitmap(bitmap);
    final String image = Base64.encodeToString(imageBytes, Base64.DEFAULT); 

图片将是您的图片串

           map.put("image ", image );

在服务器端你必须得到它作为s String并使用Base64解码器

解码它