0

I am trying to upload pic from my device to the server.Uploading pic from gallery is working fine but uploading pic from camera gives error

java.io.FileNotFoundException: /storage/emulated/0/1421501712960.jpg: open failed: ENOENT (No such file or directory)

I am using following code for uploading pic from camera.I have commented out the other paths which i tried.

 if (requestCode == REQUEST_CAMERA)
                {
                   File f = new File(Environment.getExternalStorageDirectory()
                          .toString());

                    for (File temp : f.listFiles())
                    {
                        if (temp.getName().equals("temp.jpg"))
                        {
                            f = temp;
                            break;
                        }
                    }
                    try {
                        Bitmap bm;
                        BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

                        bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
                                btmapOptions);

                       String path =android.os.Environment
                                .getExternalStorageDirectory().getPath();

                       /*String path = android.os.Environment
                                .getExternalStorageDirectory()
                                + File.separator
                                + "Phoenix" + File.separator + "default";*/



 /*             String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                            Locale.getDefault()).format(new Date());
                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "IMG_" + timeStamp + ".jpg";*/



                       f.delete();

                        File file = new File(path, String.valueOf(System
                                .currentTimeMillis()) + ".jpg");
                        new UpdateProfilePicApi().execute(file.getPath());


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



       public class UpdateProfilePicApi extends AsyncTask<String, Void, String>
        {

            String lOutput="";

            @Override
            public String doInBackground(String... realPath)
            {


                try {
                    File file = new File(realPath[0]);
                    HttpClient mHttpClient = new DefaultHttpClient();
                    HttpPost mHttpPost = new HttpPost(XYZ.URL);
                    mHttpPost.addHeader("X-MZ-Token", mSettingsManager.getAccessToken());

                    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                    entity.addPart("albumId", new StringBody(mHomeActivity.getVideoOption("album_id")));
                    entity.addPart("caption", new StringBody("photo"));
                    entity.addPart("socialType", new StringBody("sharedAlbum"));
                    entity.addPart("pic", new FileBody(file));
                    mHttpPost.setEntity(entity);

                    HttpResponse response = mHttpClient.execute(mHttpPost);

                    lOutput = ""+response.getStatusLine().getStatusCode();

                } catch (Exception e) {

                    lOutput = e.toString();

                }
                return "";
            }

            @Override
            public void onPostExecute(String result)
            {
                mProgressDialog.setVisibility(View.GONE);
                sharedPicsAdapter.notifyDataSetChanged();
                Toast.makeText(getActivity().getApplicationContext(),lOutput,Toast.LENGTH_LONG).show();
                Log.e("loutput",lOutput);

            }

            @Override
            public void onPreExecute()
            {
                mProgressDialog.setVisibility(View.VISIBLE);
            }
        }
Android Developer
  • 9,157
  • 18
  • 82
  • 139
  • What your code does: You try to find `temp.jpg` and if you find it you do absolutly nothing with it apart from deleting it. Then you try to upload a file named `.jpg`. Keep in mind that the time is different between when you asked for the image and when you received the response from camera app. – Eugen Pechanec Jan 17 '15 at 15:36
  • @EugenPechanec Can u post in answer what should be my code? – Android Developer Jan 17 '15 at 15:39
  • Not without some googling. I think there is a way to specify the filename in the image capture intent but I'm not sure. I'll post another solution which works for me. – Eugen Pechanec Jan 17 '15 at 15:50

2 Answers2

1

Excepstion says that your file donot exists on the specified path

have a check on the file path

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

        //you can create a new file name "test.jpg" in sdcard folder.
        File f = new File(Environment.getExternalStorageDirectory()
                                + File.separator + "test.jpg");
        try {

            f.createNewFile();
            //write the bytes in file
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            // remember close de FileOutput
            fo.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (f.exists()) {

            Toast.makeText(this, "Image Found : "+f.getAbsolutePath().toString(), Toast.LENGTH_SHORT).show();
             new UpdateProfilePicApi().execute(f.getAbsolutePath().toString());
        }else{
              Toast.makeText(this, "Image Not Found", Toast.LENGTH_SHORT).show();
        }


    }
}

and your intent

Intent cameraIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
Moubeen Farooq Khan
  • 2,875
  • 1
  • 11
  • 26
0

The problem is that System.currentTimeMillis() changes rapidly so between you asking for a camera input and receiving the image the value is different and you can't find the file (and that's only if you specified the file name beforehand).

I can only recommend reading and using the documentation for obtaining a full-sized image from camera. The only difference is that instead of getExternalStoragePublicDirectory() you'd use getExternalFilesDir() because you don't want the image public. If you follow the guide, the image path will be stored in String mCurrentPhotoPath; so you can upload it and delete it afterwards easily.

Eugen Pechanec
  • 37,669
  • 7
  • 103
  • 124