机器人 - 发送图片文件到服务器数据库 [英] Android - Send Image file to the Server DB

查看:138
本文介绍了机器人 - 发送图片文件到服务器数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户节省了三个数据: 名称注意图片的。正如你可以看到下面的code, 我成功地code,将姓名和注意事项发送到服务器端。 但是,我不知道如何从设备发送一个选择的图像文件到serverDB。

Users save three data: name, note and image. As you can see the code below, I succeeded to code to send the name and note to the server side. But, I have no idea how to send a selected image file from the device to the serverDB.

public class AddEditWishlists extends Activity {

    // Client-Server - Start //////////////////////
    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputDesc;

    // url to create new product
    private static String url_create_product = 
        "http://10.56.43.91/android_connect/create_product.php";


    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    // Client-Server - End //////////////////////


    //Define Variables
    private EditText inputname;
    private EditText inputnote;
    private Button upload;
    private Bitmap yourSelectedImage;
    private ImageView inputphoto;
    private Button save;
    private int id;
    private byte[] blob=null;
    byte[] image=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_wishlist);
        setUpViews();
    }

    private void setUpViews() {

        inputname = (EditText) findViewById(R.id.inputname);
        inputnote = (EditText) findViewById(R.id.inputnote);
        inputphoto = (ImageView) findViewById(R.id.inputphoto); 

        Bundle extras = getIntent().getExtras();

        if (extras != null) {
            id=extras.getInt("id");
            inputname.setText(extras.getString("name"));
            inputnote.setText(extras.getString("note"));

            image = extras.getByteArray("blob");

            if (image != null) {
                if (image.length > 3) {
                    inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
                }
            }

        }



        //Image Upload Button
        upload = (Button) findViewById(R.id.upload);
        upload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            }
        });

        // Save the data
        save = (Button) findViewById(R.id.save);

        // Save하면 발생되는 이벤트
        save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (inputname.getText().length() != 0) {
                    AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
                        @Override
                        protected Object doInBackground(Object... params) {
                            saveContact();

                            // Client-Server - Start //////////////////////////////////////
                            String name = inputname.getText().toString();
                            String description = inputnote.getText().toString();


                            // Building Parameters
                            List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                            params1.add(new BasicNameValuePair("name", name));
                            params1.add(new BasicNameValuePair("description", description));

                            // getting JSON Object
                            // Note that create product url accepts POST method
                            JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1);

                            // check log cat fro response
                            Log.d("Create Response", json.toString());

                            // check for success tag
                            try {
                                int success = json.getInt(TAG_SUCCESS);

                                if (success == 1) {
                                    // successfully created product
                                    // closing this screen
                                    finish();
                                } else {
                                    // failed to create product
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            // Client-Server - End ////////////////////////////////////

                            return null;
                        }

                        @Override
                        protected void onPostExecute(Object result) {
                            finish();
                        }
                    };

                    saveContactTask.execute((Object[]) null);

                } else {
                    AlertDialog.Builder alert = new AlertDialog.Builder(
                            AddEditWishlists.this);
                    alert.setTitle("Error In Save Wish List");
                    alert.setMessage("You need to Enter Name of the Product");
                    alert.setPositiveButton("OK", null);
                    alert.show();
                }
            }
        });
    }


    // If users save data, this will act (data -> db) 
    private void saveContact() {

        if(yourSelectedImage!=null){
            ByteArrayOutputStream outStr = new ByteArrayOutputStream();
            yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
            blob = outStr.toByteArray();
        }

        else{blob=image;}

        // Change Text type to string type to save in the DB
        SQLiteConnector sqlCon = new SQLiteConnector(this);

        if (getIntent().getExtras() == null) {
            sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
        }

        else {
            sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(),blob);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
        super.onActivityResult(requestCode, resultCode, resultdata);
        switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {
                Uri selectedImage = resultdata.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 filePath = cursor.getString(columnIndex);

                cursor.close();
                // Convert file path into bitmap image using below line.
                yourSelectedImage = BitmapFactory.decodeFile(filePath);
                inputphoto.setImageBitmap(yourSelectedImage);
            }

        }
    }

}

我怎样才能在客户端与服务器之间的注解code发送图像文件?..

How can I code between the client-server annotation to send the image file?..

推荐答案

您可以将所选影像立足64字符串,然后将字符串传递给服务器,然后服务器德code表示,

You can convert the selected image to base 64 string and then pass that string to the server and then in the server decode that,

勾选此code到图像转换为Base64,如果你有ImageView的,那么你可以这样写code,

Check this code to convert image to base64,If you have the imageView then you can write this code,

imageView.buildDrawingCache();
Bitmap bm = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();

String encodedImage = Base64.encodeToString(b , Base64.DEFAULT);

修改

在你的code,你在这一行的字节数组,

EDIT

as in your code,you have the byte array in this line,

image = extras.getByteArray("blob");

这样你就可以直接在那之后写这行code,

so you can directly write this line of code after that,

String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);

这篇关于机器人 - 发送图片文件到服务器数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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