简体   繁体   English

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

[英]how to upload image into server without using upload button in 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 = "\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 error 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)

First you have to place your uploadfile method in asynctask and call that asynctask in oncreate method of activity. 首先,您必须将uploadfile方法放在asynctask中 ,然后在活动的oncreate方法中调用该asynctask。 Call this asynctask in onCreate() in second activity. 在第二个活动中的onCreate()中调用此asynctask。 You have to download third party jar file to use multipartEntity from here. 您必须从此处下载第三方jar文件才能使用multipartEntity

If ADT 17 jars need to be put into the libs folder or they wont be packaged with the apk. 如果需要将ADT 17罐子放到libs文件夹中,否则它们将不与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();
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM