0

I am having trouble figuring out how to pass the image's uri as I need it to grab the file unless there is another way and I just don't see it (I am pretty new to this). I have the image selected working and setting the imageview's bitmap to the bitmap but now trying to have it be send to the server once the submit button is clicked.

I know I can do execute(uri); but how do I actually pull out the uri from the imageview?

Here is the code : )

public class wardrobe extends Activity implements OnClickListener {

    // set variable for the fields
    private EditText nameField, sizeField, colorField, quantityField;
    private Spinner typeField, seasonField;
    private ImageView imageview;
    private ProgressBar progressBarField;
    private TextView imageTextSelect, resImage;
    private ProgressDialog progressDialog = null;
    private int serverResponseCode = 0;
    private Button uploadImageButton, postWardrobe;
    private String upLoadServerUri = null;
    private String imagepath = null;
    private Bitmap bitmap;

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

        // image upload stuff
        imageview = (ImageView) findViewById(R.id.user_photo);
        imageTextSelect = (TextView) findViewById(R.id.imageTextSelect);

        // button for upload image
        uploadImageButton = (Button) findViewById(R.id.uploadImageButton);

        // button for posting details
        postWardrobe = (Button) findViewById(R.id.postButton);

        uploadImageButton.setOnClickListener(this);
        postWardrobe.setOnClickListener(this);



    @Override
    public void onClick(View v) {

        /**
         * Opens dialog picker, so the user can select image from the gallery.
         * The result is returned in the method <code>onActivityResult()</code>
         */
        if (v == uploadImageButton) {
            // below allows you to open the phones gallery
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Complete action using"), 1);
        }
        if (v == postWardrobe) {

                // execute the post request

                new ImageUploadTask().execute();

            }
        }

    }

    /**
     * Retrives the result returned from selecting image, by invoking the method
     * <code>selectImageFromGallery()</code>
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == 1 && null != data) {

            decodeUri(data.getData());
        }
    }

    public void decodeUri(Uri uri) {
        ParcelFileDescriptor parcelFD = null;
        try {
            parcelFD = getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor imageSource = parcelFD.getFileDescriptor();

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(imageSource, null, o);

            // the new size we want to scale to
            final int REQUIRED_SIZE = 1024;

            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
                    break;
                }
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);

            imageview.setImageBitmap(bitmap);

            // can take off below just shows path
            imageTextSelect.setText("select : " + uri);
        } catch (FileNotFoundException e) {
            // handle errors
        } catch (IOException e) {
            // handle errors
        } finally {
            if (parcelFD != null)
                try {
                    parcelFD.close();
                } catch (IOException e) {
                    // ignored
                }
        }
    }

PART I AM TRYING TO GET WORKING : )

    private class ImageUploadTask extends AsyncTask<Void, Void, String> {



What I need is the uri or the file...
String fileName = imagepath;
File sourceFile = new File(imagepath);


                private String webAddressToPost = "http://10.0.2.2/wardrobe";
                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;


                // private ProgressDialog dialog
                private ProgressDialog progressDialog = new ProgressDialog(
                                wardrobe.this);

                @Override
                protected void onPreExecute() {
                        progressDialog.setMessage("Uploading...");
                        progressDialog.show();
                }

                @Override
                protected String doInBackground(Void... arg0) {



if (!sourceFile.isFile()) {

                        progressDialog.dismiss();

                        Log.e("uploadFile", "Source File not exist :" + imagepath);

                        runOnUiThread(new Runnable() {
                                public void run() {
                                        imageTextSelect.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("uploaded_file", fileName);

                                dos = new DataOutputStream(conn.getOutputStream());

                                dos.writeBytes(twoHyphens + boundary + lineEnd);
                                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                                + fileName + "\"" + 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 necesssary 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) {


                                                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                                                        + " F:/wamp/wamp/www/uploads";
                                                        imageTextSelect.setText(msg);
                                                        Toast.makeText(wardrobe.this,
                                                                        "File Upload Complete.", Toast.LENGTH_SHORT)
                                                                        .show();

                                }

                                // close the streams //
                                fileInputStream.close();
                                dos.flush();
                                dos.close();

                        } catch (MalformedURLException ex) {

                                progressDialog.dismiss();
                                ex.printStackTrace();


                                                imageTextSelect
                                                                .setText("MalformedURLException Exception : check script url.");
                                                Toast.makeText(wardrobe.this, "MalformedURLException",
                                                                Toast.LENGTH_SHORT).show();


                                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
                        } catch (Exception e) {

                                progressDialog.dismiss();
                                e.printStackTrace();


                                                imageTextSelect.setText("Got Exception : see logcat ");
                                                Toast.makeText(wardrobe.this,
                                                                "Got Exception : see logcat ",
                                                                Toast.LENGTH_SHORT).show();

                                Log.e("Upload file to server Exception",
                                                "Exception : " + e.getMessage(), e);
                        }


}
Lion789
  • 4,402
  • 12
  • 58
  • 96
  • You can use FTP instead of HTTP post. Get your Bitmap like this ... Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap(); – elbuild Jan 17 '14 at 23:59
  • I rather use http, i know there are bunch of debates on them but I am not trying to get into complex grounds with this, thanks though, I feel like there has to be an easy answer to this question... how do people do it lol – Lion789 Jan 18 '14 at 00:03

1 Answers1

0

You have to use http post with multipart data to upload images.

try this link

Community
  • 1
  • 1
Suneel Prakash
  • 389
  • 5
  • 7