如何在将文件上传到服务器时重命名文件?

时间:2013-06-07 05:37:48

标签: android image upload file-rename

我正在开发一个Android应用程序,我在网格视图中从图库中获取所有图像,并将其与复选框一起显示。我可以选择图像并将多个图像上传到服务器....但现在在将其上传到服务器之前我需要根据我的惯例重命名我选择的图像.....我无法做到这一点! 我该怎么办? 任何人都有任何想法?请帮忙!!我真的需要这样做!! 我正在数组列表中获取所选图像的路径...

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

}

我试图在上传时更改名称,但我找不到文件异常...

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()方法:

 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 
     } 

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)

1 个答案:

答案 0 :(得分: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);
    }