1

I am developing an android app where i am getting all the images from the gallery in a grid view and displaying it along with a checkbox..i m able to select the images and upload multiple images to the server....but now before uploading it to the server i need to rename the images i am selecting as per my conventions.....m not able to do that!! How do i go about that??? anybody has any idea?? Please help!! I really need to do this!! i am getting the paths of the selected images in an array list ...

public void btnChoosePhotosClick(View v){

    selectedItems=new ArrayList<String>();
    **selectedItems** = imageAdapter.getCheckedItems();
    Toast.makeText(MultiPhotoSelectActivity.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show();
    Log.d(MultiPhotoSelectActivity.class.getSimpleName(), "Selected Items: " + selectedItems.toString());

}

and i am trying to change the name while uploading but i get file not found exception...

UploadToServer upload=new UploadToServer();
protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        String imagepath;
        String imagename;
        doctype_imagename="1234_doctype_pageno_"+System.currentTimeMillis()+".jpg";

        for( int i=0;i<selectedItems.size();i++)
        {
            if (isCancelled()) {
                break;
            } 
            else
            {   try
                {

                    imagepath=selectedItems.get(i);
                    //upload.uploadFile(imagepath);
                    sourcefile=new File(imagepath);
                    imagename=imagepath.substring(imagepath.lastIndexOf("/")+1);
                    from=new File(Environment.getExternalStorageDirectory(),imagename);
                    to=new File(Environment.getExternalStorageDirectory(),doctype_imagename);

                    from.renameTo(to);

                    upload.uploadFile(to.getAbsolutePath());

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

                        ftp=null;
                }

            }
        }
    return null;
    }

upoalFile() method:

 public int uploadFile(String sourceFileUri) {

      String fileName = 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); 
      upLoadServerUri = "http://10.0.2.2/android/UploadToServer.php";

           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){

                  Log.e("Upload ", "Image Uploaded Successfully");      
               }    

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

          } catch (MalformedURLException ex) {


              ex.printStackTrace();



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


              e.printStackTrace();


          }

          return serverResponseCode; 

        // End else block 
     } 

the logcat:

06-07 06:13:05.538: W/System.err(1011): java.io.FileNotFoundException: /mnt/sdcard/1234_doctype_pageno_1370585584714.jpg: open failed: ENOENT (No such file or directory)
06-07 06:13:05.789: W/System.err(1011):     at java.io.FileInputStream.<init>(FileInputStream.java:78)
06-07 06:13:05.848: W/System.err(1011):     at  com.example.sampletestapp.UploadToServer.uploadFile(UploadToServer.java:61)
06-07 06:13:05.848: W/System.err(1011):     at com.example.sampletestapp.MultiPhotoSelectActivity$SaveImage.doInBackground(MultiPhotoSelectActivity.java:235)
06-07 06:13:05.848: W/System.err(1011):     at com.example.sampletestapp.MultiPhotoSelectActivity$SaveImage.doInBackground(MultiPhotoSelectActivity.java:1)
06-07 06:13:05.848: W/System.err(1011):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-07 06:13:05.848: W/System.err(1011):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-07 06:13:05.858: W/System.err(1011):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-07 06:13:05.868: W/System.err(1011):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-07 06:13:05.868: W/System.err(1011):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-07 06:13:05.868: W/System.err(1011):     at java.lang.Thread.run(Thread.java:856)
06-07 06:13:05.868: W/System.err(1011): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
shivani
  • 746
  • 3
  • 22
  • 40
  • Possible duplicate of http://stackoverflow.com/questions/10424997/android-how-to-rename-a-file – Triode Jun 07 '13 at 05:47
  • @Simon yes i did google this topic for a day...but could not get what i needed..i need to pass the file path to that **uploadFile() method**..how do get the path after renaming it?? my code shows FileNotFound Exception – shivani Jun 07 '13 at 05:51
  • check your path in to.getAbsolutePath() ..is it null or not.. – Sagar Maiyad Jun 07 '13 at 06:18
  • @Segi i put a toast message for this `Toast.makeText(MultiPhotoSelectActivity.this, "New file path: "+to.getAbsolutePath(),Toast.LENGTH_LONG).show();` and it is showing the path.. – shivani Jun 07 '13 at 06:24
  • then store into global variable...and use that variable for pass in method.. – Sagar Maiyad Jun 07 '13 at 06:26
  • is your imagepath correct? How are you filling the path in selectedItems? Like /mnt/sdcard doesnt exist. – Tarun Jun 07 '13 at 06:28

1 Answers1

0
String pathvalue;

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
             if (requestCode == SELECT_FILE) {
                Uri selectedImageUri = data.getData();

                String tempPath = getPath(selectedImageUri, ServiceEntry.this);
                Bitmap bm;
                System.out.println(tempPath);
                File filename = new File(tempPath);
                pathvalue = filename.getAbsolutePath()
            }
        }
    }

    public String getPath(Uri uri, Activity activity) {
        String[] projection = { MediaColumns.DATA };
        Cursor cursor = activity
                .managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99
  • i just did this but why is it not recognising the file path??? i am still getting file not found exception... – shivani Jun 07 '13 at 06:56
  • then look at your gallery, is there that file in it .? – Sagar Maiyad Jun 07 '13 at 07:04
  • the file in the sdcard is empty! there is file with that name but its empty! s getting images by this code `MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID` different from getting images by this code`Environment.getExternalStorageDirectory()` ??? do they return different paths?? – shivani Jun 07 '13 at 07:29
  • can u suggest what can be done in this case??? how do i rename images using this path `MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID ` and upload it to the server?? any idea?? any example u can think of which i can refer?? – shivani Jun 07 '13 at 07:41
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/31383/discussion-between-segi-and-shivani) – Sagar Maiyad Jun 07 '13 at 08:39