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

1 回答 1

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);
    }
于 2013-06-07T06:41:40.170 回答