通过http-post将数据和图像提交到mysql

时间:2014-09-03 08:30:36

标签: php android mysql http-post

将imageView与其他字段一起提交到mysql,其中真实图像存储在localhost中的文件夹中,而mysql表中的图像路径,但图像和其他字段未按预期存储。

我尝试过这个link

的代码

Java代码:

    public class AddProduct extends Activity implements OnClickListener {

    String[] types;
    String[] subcategories;
    Spinner spinnerCategory,spinnerSubcategory;

    EditText editproductname,editproductdescrip,editproductprice,editmoreinfo,editcategory;
    TextView txtStatus; 
    String image_str;

    ImageView imageview;
    public Button Addproduct,btnselectpic, uploadButton;
    ProgressDialog dialog = null;
    public static String PRODUCT_URL = "http:localhost/folder1/addproducts.php";
    public static final String TAG_SUCCESS = "success";
    public static final String TAG_MESSAGE = "message";
    private int serverResponseCode = 0;
    private String upLoadServerUri;
    private String imagepath = null;

    JSONParser jsonParser = new JSONParser();

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

        txtStatus = (TextView)findViewById(R.id.status);
        spinnerCategory = (Spinner) findViewById(R.id.spinnercategory);
        spinnerSubcategory = (Spinner) findViewById(R.id.spinnersubcategory);
        editproductname=(EditText)findViewById(R.id.proname);
        editproductdescrip=(EditText)findViewById(R.id.prodesc);
        editproductprice=(EditText)findViewById(R.id.prodprice);
        editmoreinfo=(EditText)findViewById(R.id.prodinfo);
        btnselectpic = (Button) findViewById(R.id.button_selectpic);
          uploadButton = (Button) findViewById(R.id.uploadButton);
        Addproduct=(Button)findViewById(R.id.btnproduct);
        imageview = (ImageView) findViewById(R.id.imageViewUpload);

        btnselectpic.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        Addproduct.setOnClickListener(this);
        upLoadServerUri = "http://localhost/folder1/addproducts.php";
          ImageView img = new ImageView(this);

      //set Array for parent spinner "Category"
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.types, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerCategory.setAdapter(adapter);

            //set Array for child spinner Subcategory1
           final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.category1sub, android.R.layout.simple_spinner_item);
            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerSubcategory.setAdapter(adapter1);

            //set Array for child spinner Subcategory2
           final ArrayAdapter<CharSequence> adapter2= ArrayAdapter.createFromResource(this, R.array.category2sub, android.R.layout.simple_spinner_item);
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerSubcategory.setAdapter(adapter2);

            //set Array for child spinner Subcategory3
            final ArrayAdapter<CharSequence> adapter3= ArrayAdapter.createFromResource(this, R.array.category3sub,android.R.layout.simple_spinner_item);
            adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerSubcategory.setAdapter(adapter3);

            spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent, View view,int position, long id){
                    String selectedItem = parent.getItemAtPosition(position).toString();
                    if(selectedItem.trim().equals("Electronics")){
                        spinnerSubcategory.setAdapter(adapter1);
                    }
                    else if(selectedItem.trim().equals("Fashion")){
                        spinnerSubcategory.setAdapter(adapter2);
                    }
                    else if(selectedItem.trim().equals("HomeAppliance")){
                        spinnerSubcategory.setAdapter(adapter3);
                    }
                    types = getResources().getStringArray(R.array.types);
                    Toast.makeText(getBaseContext(), "You have selected : " +types[position], Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // TODO Auto-generated method stub  
                }   
            });             
    }

    @Override
    public void onClick(View arg0) {
        if (arg0 == btnselectpic) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Complete action using"), 1);
        } else if (arg0 == uploadButton) {

            dialog = ProgressDialog.show(AddProduct.this, "", "Uploading file...", true);
            txtStatus.setText("uploading started.....");
            new Thread(new Runnable() {
                public void run() {

                    uploadFile(imagepath);
                }
            }).start();
        } else if (arg0 == Addproduct) {

            dialog = ProgressDialog.show(AddProduct.this, "","Uploading file...", true);
            txtStatus.setText("uploading started.....");
            new Thread(new Runnable() {
                public void run() {
                     new CreateProduct().execute();
                      //uploadFile(imagepath);
                } 
            }).start();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1 && resultCode == RESULT_OK) {
        // Bitmap photo = (Bitmap) data.getData().getPath();

        Uri selectedImageUri = data.getData();
        imagepath = getRealPathFromURI(selectedImageUri);
        Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
        imageview.setImageBitmap(bitmap);
        txtStatus.setText("Uploading file path:" + imagepath);
    }
}

    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if(cursor.moveToFirst()){;
           int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           res = cursor.getString(column_index);
        }
        cursor.close();
        return res;    
    }   

    class CreateProduct extends AsyncTask<String, String, String> {
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(AddProduct.this);
            //dialog.setMessage("Creating Product...");
            dialog.setIndeterminate(false);
            dialog.setCancelable(true);
            dialog.show();
            }
        @Override
        protected String doInBackground(String... paramss) {
            int success;
            String strtype = spinnerCategory.getSelectedItem().toString();
            String strsubtype = spinnerSubcategory.getSelectedItem().toString();
            String productname=editproductname.getText().toString(); 
           String productdescription=editproductdescrip.getText().toString();
            String productprice=editproductprice.getText().toString();
            String moreinfo=editmoreinfo.getText().toString();

        try {
            //Building parameter
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("txtcategory",strtype));
            params.add(new BasicNameValuePair("txtsubcategory",strsubtype));
            params.add(new BasicNameValuePair("txtproductname", productname));
            params.add(new BasicNameValuePair("txtproductdescription", productdescription));
            params.add(new BasicNameValuePair("txtproductprice", productprice));
            params.add(new BasicNameValuePair("txtmoreinfo",moreinfo));     

            Log.d("request!", "starting");
            //Posting user data to script
            JSONObject json = jsonParser.makeHttpRequest(PRODUCT_URL, "POST",params);
            //full json response
            Log.d("Adding Product", json.toString());
            //json success element
            success = json.getInt(TAG_SUCCESS);
            if(success == 1){
            Log.d("Product Added!", json.toString());
            Intent c= new Intent(AddProduct.this, ProductList.class);
            startActivity(c);
            finish();
            return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Product not added",json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);
                }
            }catch (JSONException e){
                e.printStackTrace();
                }
        return null;
        }

        protected void onPostExecute(String file_url) {
        //dismiss the dialog once deleted
        dialog.dismiss();
        if (file_url != null) {
            Toast.makeText(AddProduct.this, file_url, Toast.LENGTH_LONG).show();
            }
        }
    }

    ///Upload image separately,

    public int uploadFile(String sourceFileUri) {

        String tmp_name = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {
            dialog.dismiss();
            Log.e("uploadFile", "Source File not exist :" + imagepath);

            runOnUiThread(new Runnable() {
                public void run() {
                    //messageText.setText("Source File not exist :" + imagepath);
                }
            });
            return 0;
        } else {
            try {
                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("image", tmp_name);

                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\""+tmp_name+ "\"" +lineEnd);
                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                // send multipart form data necessary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is: "+ serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) {

                    runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here: \n\n"+" C:/localhost/iagent/images";
                            //messageText.setText(msg);
                            Toast.makeText(AddProduct.this,"File Upload Complete.", Toast.LENGTH_SHORT).show();
                        }   }); }

                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        txtStatus.setText("MalformedURLException Exception : check script url.");
                        Toast.makeText(AddProduct.this,"MalformedURLException", Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {
                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                       // messageText.setText("Got Exception : see logcat ");
                        Toast.makeText(AddProduct.this,"Got Exception : see logcat ",Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception","Exception : " + e.getMessage(), e);
            }
            dialog.dismiss();
            return serverResponseCode;
        } // End else block
    }   
}`

使用PHP代码 -

<?php

$category = $_POST["txtcategory"]; 
$subcategory = $_POST["txtsubcategory"]; 
$productname = $_POST["txtproductname"];
$productdescrip = $_POST["txtproductdescription"];
$productprice = $_POST["txtproductprice"];
$moreinfo = $_POST["txtmoreinfo"];  
$file   =$_FILES['image']['tmp_name'];
//file_put_contents('newImage.JPEG',$decoded);


if($productname == null || $productprice == null){
$response["success"] = 0;
$response["message"] = "Field is vacant";
die(json_encode($response));
}

$con=mysqli_connect("localhost","user","passowrd","db");
// Check connection
if (mysqli_connect_errno()) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
///
try{
if (!isset($_FILES['image']['tmp_name'])) {
    echo "";
    }else{
    $file=$_FILES['image']['tmp_name'];
    $image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $image_name= addslashes($_FILES['image']['name']);

            move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);

        $location="http://192.168.1.5/iagent/images/" . $_FILES["image"]["name"];
            //$caption=$_POST['caption'];

    $save=mysql_query("INSERT INTO products (pro_img_path) VALUES ('$location')");
            //header("location: addimage.php");
    }                   

//$result = mysqli_query($con,"INSERT INTO products(category, subcategory,product_name,product_price) VALUES ('$category','$subcategory','$productname','$productprice')");
$result = mysqli_query($con,"INSERT INTO products(category,subcategory,product_name,product_descrip,product_price,more_info) VALUES ('$category','$subcategory','$productname','$productdescrip','$productprice','$moreinfo')");

$response["success"] = 1;
$response["message"] = "Product Added Successful!";
die(json_encode($response));
}
catch(Exception $e){
$response["success"] = 0;
$response["message"] = "Product Not Added";
die(json_encode($response));
}
mysqli_close($con);
?>

Logcat错误如下

09-03 03:33:11.637: D/dalvikvm(1316): GC_FOR_ALLOC freed 59K, 5% free 2948K/3088K, paused 78ms, total 82ms
09-03 03:33:11.637: I/dalvikvm-heap(1316): Grow heap (frag case) to 3.558MB for 635812-byte allocation
09-03 03:33:11.697: D/dalvikvm(1316): GC_FOR_ALLOC freed 2K, 4% free 3566K/3712K, paused 52ms, total 52ms
09-03 03:33:12.247: I/Choreographer(1316): Skipped 64 frames!  The application may be doing too much work on its main thread.
09-03 03:33:12.367: D/gralloc_goldfish(1316): Emulator without GPU emulation detected.
09-03 03:33:12.737: I/Choreographer(1316): Skipped 47 frames!  The application may be doing too much work on its main thread.
09-03 03:33:15.417: I/Choreographer(1316): Skipped 102 frames!  The application may be doing too much work on its main thread.
09-03 03:33:15.867: I/Choreographer(1316): Skipped 106 frames!  The application may be doing too much work on its main thread.
09-03 03:33:18.307: I/Choreographer(1316): Skipped 176 frames!  The application may be doing too much work on its main thread.
09-03 03:33:20.487: D/dalvikvm(1316): GC_FOR_ALLOC freed 86K, 5% free 3904K/4068K, paused 269ms, total 275ms
09-03 03:33:23.167: I/Choreographer(1316): Skipped 121 frames!  The application may be doing too much work on its main thread.
09-03 03:33:24.457: I/Choreographer(1316): Skipped 35 frames!  The application may be doing too much work on its main thread.
09-03 03:33:24.847: I/Choreographer(1316): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-03 03:33:26.757: I/Choreographer(1316): Skipped 36 frames!  The application may be doing too much work on its main thread.
09-03 03:33:30.887: W/IInputConnectionWrapper(1316): showStatusIcon on inactive InputConnection
09-03 03:33:46.937: D/dalvikvm(1316): GC_FOR_ALLOC freed 126K, 5% free 4271K/4476K, paused 273ms, total 292ms
09-03 03:33:47.337: I/Choreographer(1316): Skipped 31 frames!  The application may be doing too much work on its main thread.
09-03 03:33:48.987: I/Choreographer(1316): Skipped 136 frames!  The application may be doing too much work on its main thread.
09-03 03:33:53.847: I/Choreographer(1316): Skipped 151 frames!  The application may be doing too much work on its main thread.
09-03 03:33:54.607: I/Choreographer(1316): Skipped 116 frames!  The application may be doing too much work on its main thread.
09-03 03:33:55.037: I/Choreographer(1316): Skipped 99 frames!  The application may be doing too much work on its main thread.
09-03 03:33:55.247: D/dalvikvm(1316): GC_FOR_ALLOC freed 470K, 12% free 4314K/4860K, paused 71ms, total 80ms
09-03 03:33:55.247: I/Choreographer(1316): Skipped 32 frames!  The application may be doing too much work on its main thread.
09-03 03:33:55.857: I/uploadFile(1316): HTTP Response is: OK: 200
09-03 03:33:56.127: I/Choreographer(1316): Skipped 63 frames!  The application may be doing too much work on its main thread.
09-03 03:33:56.477: I/Choreographer(1316): Skipped 85 frames!  The application may be doing too much work on its main thread.
09-03 03:33:57.007: I/Choreographer(1316): Skipped 34 frames!  The application may be doing too much work on its main thread.
09-03 03:34:22.467: W/dalvikvm(1316): threadid=14: thread exiting with uncaught exception (group=0xb3a74ba8)
09-03 03:34:22.527: E/AndroidRuntime(1316): FATAL EXCEPTION: Thread-101
09-03 03:34:22.527: E/AndroidRuntime(1316): Process: crawes.product.iagent, PID: 1316
09-03 03:34:22.527: E/AndroidRuntime(1316): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
09-03 03:34:22.527: E/AndroidRuntime(1316):     at android.os.Handler.<init>(Handler.java:200)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at android.os.Handler.<init>(Handler.java:114)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at android.app.Dialog.<init>(Dialog.java:109)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at android.app.AlertDialog.<init>(AlertDialog.java:114)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at android.app.AlertDialog.<init>(AlertDialog.java:98)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at crawes.product.iagent.AddProduct$CreateProduct.onPreExecute(AddProduct.java:193)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at android.os.AsyncTask.execute(AsyncTask.java:535)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at crawes.product.iagent.AddProduct$3.run(AddProduct.java:154)
09-03 03:34:22.527: E/AndroidRuntime(1316):     at java.lang.Thread.run(Thread.java:841)
09-03 03:34:23.207: I/Choreographer(1316): Skipped 183 frames!  The application may be doing too much work on its main thread.
09-03 03:34:24.047: I/Choreographer(1316): Skipped 191 frames!  The application may be doing too much work on its main thread.
09-03 03:34:24.707: I/Choreographer(1316): Skipped 126 frames!  The application may be doing too much work on its main thread.
09-03 03:34:25.697: I/Choreographer(1316): Skipped 253 frames!  The application may be doing too much work on its main thread.
09-03 03:34:26.427: I/Choreographer(1316): Skipped 190 frames!  The application may be doing too much work on its main thread.
09-03 03:34:26.657: I/Choreographer(1316): Skipped 42 frames!  The application may be doing too much work on its main thread.
09-03 03:34:28.137: E/WindowManager(1316): android.view.WindowLeaked: Activity crawes.product.iagent.AddProduct has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b3e8c290 V.E..... R.....ID 0,0-456,144} that was originally added here
09-03 03:34:28.137: E/WindowManager(1316):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
09-03 03:34:28.137: E/WindowManager(1316):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
09-03 03:34:28.137: E/WindowManager(1316):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
09-03 03:34:28.137: E/WindowManager(1316):  at android.app.Dialog.show(Dialog.java:286)
09-03 03:34:28.137: E/WindowManager(1316):  at android.app.ProgressDialog.show(ProgressDialog.java:116)
09-03 03:34:28.137: E/WindowManager(1316):  at android.app.ProgressDialog.show(ProgressDialog.java:99)
09-03 03:34:28.137: E/WindowManager(1316):  at crawes.product.iagent.AddProduct.onClick(AddProduct.java:150)
09-03 03:34:28.137: E/WindowManager(1316):  at android.view.View.performClick(View.java:4438)
09-03 03:34:28.137: E/WindowManager(1316):  at android.view.View$PerformClick.run(View.java:18422)
09-03 03:34:28.137: E/WindowManager(1316):  at android.os.Handler.handleCallback(Handler.java:733)
09-03 03:34:28.137: E/WindowManager(1316):  at android.os.Handler.dispatchMessage(Handler.java:95)
09-03 03:34:28.137: E/WindowManager(1316):  at android.os.Looper.loop(Looper.java:136)
09-03 03:34:28.137: E/WindowManager(1316):  at android.app.ActivityThread.main(ActivityThread.java:5017)
09-03 03:34:28.137: E/WindowManager(1316):  at java.lang.reflect.Method.invokeNative(Native Method)
09-03 03:34:28.137: E/WindowManager(1316):  at java.lang.reflect.Method.invoke(Method.java:515)
09-03 03:34:28.137: E/WindowManager(1316):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-03 03:34:28.137: E/WindowManager(1316):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-03 03:34:28.137: E/WindowManager(1316):  at dalvik.system.NativeStart.main(Native Method)
09-03 03:34:28.137: I/Choreographer(1316): Skipped 133 frames!  The application may be doing too much work on its main thread.
09-03 03:39:22.877: I/Process(1316): Sending signal. PID: 1316 SIG: 9

0 个答案:

没有答案