2014-03-12 65 views
0

我想上傳圖像到服務器而無需使用上傳按鈕,我發送圖像路徑下一個活動,我們有圖像預覽..但我的問題如何上傳該圖像到服務器,而不使用點擊活動......這預覽圖像應上傳到server..Please幫助我..如何上傳圖像到服務器,而不使用上傳按鈕在android

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

       setContentView(R.layout.cam); 
    ImageView view = (ImageView) findViewById(R.id.imageView1); 



     image_path = getIntent().getStringExtra("path"); 
     Bitmap bitmap1 = BitmapFactory.decodeFile(image_path); 
     //Log.i(path, "image path in cam activity"); 
     view.setImageBitmap(bitmap1); 

     upLoadServerUri = "http://xxxhasdghs.com/apps/upload.php"; 


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


      if (!sourceFile.isFile()) { 

       //dialog.dismiss(); 

       //Log.e("uploadFile", "Source File not exist :"+image_path); 

       runOnUiThread(new Runnable() { 
        public void run() { 
         // messageText.setText("Source File not exist :"+ imagepath); 
         Toast.makeText(Cam.this, "Source File not exist :", Toast.LENGTH_SHORT).show(); 
        } 
       }); 

       return 0; 

      } 
      else 
      { 
       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("image", fileName); 

         dos = new DataOutputStream(conn.getOutputStream()); 

         dos.writeBytes(twoHyphens + boundary + lineEnd); 
         dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_img\";filename=\"" 
               + fileName + "\"" + lineEnd); 
         //Log.i("image value in php", mail); 
         dos.writeBytes(lineEnd); 


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

         runOnUiThread(new Runnable() { 
          public void run() { 
           String msg = "File Upload Completed.\n\n See uploaded file here : \n\n" 
             +" F:/wamp/wamp/www/uploads"; 
           //messageText.setText(msg); 
           //Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show(); 
           Toast.makeText(Cam.this, "File Upload Complete.", Toast.LENGTH_SHORT).show(); 
          } 
         });     
        }  

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


       } catch (MalformedURLException ex) { 

        dialog.dismiss(); 
        ex.printStackTrace(); 

        runOnUiThread(new Runnable() { 
         public void run() { 
         // messageText.setText("MalformedURLException Exception : check script url."); 
         // Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show(); 
          Toast.makeText(Cam.this, "MalformedURLException", Toast.LENGTH_SHORT).show(); 
         } 
        }); 

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

        dialog.dismiss(); 
        e.printStackTrace(); 

        runOnUiThread(new Runnable() { 
         public void run() { 
          //messageText.setText("Got Exception : see logcat "); 
          //Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show(); 
          Toast.makeText(Cam.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show(); 
         } 
        }); 
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
       } 
       dialog.dismiss(); 

       return serverResponseCode; 

      } // End else block 


    } 

     } 

logcat的錯誤

03-12 12:59:23.703: E/AndroidRuntime(26390): FATAL EXCEPTION: AsyncTask #2 
03-12 12:59:23.703: E/AndroidRuntime(26390): java.lang.RuntimeException: An error occured while executing doInBackground() 
03-12 12:59:23.703: E/AndroidRuntime(26390): at android.os.AsyncTask$3.done(AsyncTask.java:299) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.lang.Thread.run(Thread.java:841) 
03-12 12:59:23.703: E/AndroidRuntime(26390): Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.mime.MultipartEntity 
03-12 12:59:23.703: E/AndroidRuntime(26390): at com.example.slimcell.CameraActivity$ImageUploadTask.doInBackground(CameraActivity.java:101) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at com.example.slimcell.CameraActivity$ImageUploadTask.doInBackground(CameraActivity.java:1) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at android.os.AsyncTask$2.call(AsyncTask.java:287) 
03-12 12:59:23.703: E/AndroidRuntime(26390): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
+0

你的'onCreate'方法在哪裏?從'onCreate'調用你的'uploadFile'方法。 – DroidDev

+0

如何在我的代碼中爲uploadFile創建onCreate ..可以發佈代碼.. – sandy

回答

1

首先,你必須把你的uploadfile方法asynctask並在oncreate meth中調用asynctask活動的活動。在第二個activity中調用onCreate()中的asynctask。您必須下載第三方jar文件以使用here.

中的multipartEntity如果ADT 17罐需要放入libs文件夾中,或者它們不會與apk打包在一起。因此,要麼將它們放到libs中,要麼轉到「configure Build Path ..」 - >「Order and Export」,然後單擊瓶子旁邊的複選框。

class ImageUploadTask extends AsyncTask<Void, Void, String> { 
private String webAddressToPost = "Your URL"; 

// private ProgressDialog dialog; 
private ProgressDialog dialog = new ProgressDialog(MainActivity.this); 

@Override 
protected void onPreExecute() { 
    dialog.setMessage("Uploading..."); 
    dialog.show(); 
} 

@Override 
protected String doInBackground(Void... params) { 
    try { 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpContext localContext = new BasicHttpContext(); 
    HttpPost httpPost = new HttpPost(webAddressToPost); 

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    bitmap.compress(CompressFormat.JPEG, 100, bos); 
    byte[] data = bos.toByteArray(); 
    String file = Base64.encodeBytes(data); 

    entity.addPart("uploaded", new StringBody(file)); 
    entity.addPart("someOtherStringToSend", new StringBody("your string here")); 

    httpPost.setEntity(entity); 
    HttpResponse response = httpClient.execute(httpPost,localContext); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent(), "UTF-8")); 

    String sResponse = reader.readLine(); 
    return sResponse; 
    } catch (Exception e) { 
    // something went wrong. connection with the server error 
    } 
    return null; 
} 

@Override 
protected void onPostExecute(String result) { 
    dialog.dismiss(); 
    Toast.makeText(getApplicationContext(), "file uploaded",Toast.LENGTH_LONG).show(); 
} 
} 
+0

檢查已編輯的答案。 –

+0

非常感謝它..我工作.. ..謝謝.. – sandy

+0

@ Harshit:圖像沒有上傳到服務器..請幫助我.. – sandy

相關問題