使用HTTP Post MultipartEntity从相机上传pics时出现java.io.FileNotFoundException

时间:2015-01-17 14:00:26

标签: android http android-camera filenotfoundexception multipartentity

我正在尝试将图片从我的设备上传到服务器。从图库上传图片工作正常,但从相机上传图片会出错

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

我正在使用以下代码从相机上传图片。我已经注释了我尝试过的其他路径。

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

2 个答案:

答案 0 :(得分:1)

Excepstion表示您的文件不存在于指定的路径上

检查文件路径

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


    }
}

和你的意图

Intent cameraIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);

答案 1 :(得分:0)

问题在于System.currentTimeMillis()变化很快,因此在您要求输入摄像头和接收图像之间,值不同,您无法找到该文件(只有当您找到该文件时才能找到该文件事先指定了文件名。)

我只能推荐阅读和使用documentation for obtaining a full-sized image from camera。唯一的区别是,您不是getExternalStoragePublicDirectory()而是使用getExternalFilesDir(),因为您不希望公开图片。 如果您按照指南操作,图片路径将存储在String mCurrentPhotoPath;中,以便您可以上传并随后将其删除。