douzhong3038 2014-03-12 06:12
浏览 52
已采纳

如何在不使用android中的上传按钮的情况下将图像上传到服务器

I want to upload image to server without using upload button, i am sending image path to next activity in that activity we have image preview..but my question how to upload that image into server without using click activity...that preview image should uploaded into server..Please help me..

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 = "
";
          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.

 See uploaded file here : 

"
                                      +" 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 error

   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)
  • 写回答

1条回答 默认 最新

  • duanguilin2007 2014-03-12 06:16
    关注

    First you have to place your uploadfile method in asynctask and call that asynctask in oncreate method of activity. Call this asynctask in onCreate() in second activity. You have to download third party jar file to use multipartEntity from here.

    If ADT 17 jars need to be put into the libs folder or they wont be packaged with the apk. So either put them into libs or go to "configure Build Path.."->"Order and Export" and click the checkboxes next to your jars.

    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();
     }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失