机器人 - 发送图片文件与POST请求的服务器数据库 [英] Android - Sending Image file to the Server DB with POST Request

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

问题描述

我'工作在客户端服务器通信在我的应用程序。 我需要发送的产品的产品介绍和图片名称。 用户可以保存数据后,这些数据将保存在的心愿。 我想这些数据发送到服务器数据库。 我成功发送它们的名称和说明到服务器的文本数据,但我真的不知道如何发送图像文件。 这是我的code。

I'am working on client-server communication on my app. I need to send name of the product, description and photo of the product. Users can save the data and after that those data will save on the wishlist. And I want to send these data to the Server DB. I succeeded to send text data which are name and description to the server, but i don't really know how to send image file. This is my code.

AddEditWishlists.java

AddEditWishlists.java

public class AddEditWishlists extends Activity {

// Client-Server - Start //////////////////////

JSONParser jsonParser = new JSONParser();

// 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);
        }

    }
}

}

create_product.php

create_product.php

<?php

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['description'])) {

$name = $_POST['name'];
$description = $_POST['description'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, description) VALUES('$name', '$description')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
  }
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}

?>

您可以请给我一些建议,以图像文件发送到服务器?

could you please give me some suggestions to send image file to the server?

推荐答案

这是另一种方式发送图像服务器

This is another way send image on server

公共类UploadImage延伸活动{

public class UploadImage extends Activity {

InputStream inputStream;
    @Override
public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_image_upload);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);         
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
        byte [] byte_arr = stream.toByteArray();
        String image_str = Base64.encodeBytes(byte_arr);
        ArrayList<namevaluepair> nameValuePairs = new  ArrayList<namevaluepair>();

        nameValuePairs.add(new BasicNameValuePair("image",image_str));

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.0.23/Upload_image_ANDROID/upload_image.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            String the_string_response = convertResponseToString(response);
            Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
        }catch(Exception e){
              Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
              System.out.println("Error in http connection "+e.toString());
        }
    }

    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

         String res = "";
         StringBuffer buffer = new StringBuffer();
         inputStream = response.getEntity().getContent();
         int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
         Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
         if (contentLength < 0){
         }
         else{
                byte[] data = new byte[512];
                int len = 0;
                try
                {
                    while (-1 != (len = inputStream.read(data)) )
                    {
                        buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                try
                {
                    inputStream.close(); // closing the stream…..
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                res = buffer.toString();     // converting stringbuffer to string…..

                Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
                //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
         }
         return res;
    }

}

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

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