2014-10-25 2 views
0

Это мой код.Загрузить видео на сервер с android sdcard

package com.example.upload; 

import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

    TextView tv; 
    Button b; 
    int serverResponseCode = 0; 
    ProgressDialog dialog = null; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     b = (Button)findViewById(R.id.but); 
     tv = (TextView)findViewById(R.id.tv); 
     tv.setText("Uploading file path :- '/storage/sdcard/android_1.png'"); 

     b.setOnClickListener(new OnClickListener() {    
      @Override 
      public void onClick(View v) { 
       dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true); 
       new Thread(new Runnable() { 
         public void run() { 
          runOnUiThread(new Runnable() { 
            public void run() { 
             tv.setText("uploading started....."); 
            } 
           });      
         int response= uploadFile("/storage/sdcard/android_1.png"); 
         System.out.println("RES : " + response);       
         } 
         }).start();   
       } 
     }); 
    } 

    public int uploadFile(String sourceFileUri) { 
      String upLoadServerUri = "http://10.0.2.2/upload_test/upload_media_test.php"; 
      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()) { 
      Log.e("uploadFile", "Source File Does not exist"); 
      return 0; 
      } 
       try { // open a URL connection to the Servlet 
       FileInputStream fileInputStream = new FileInputStream(sourceFile); 
       URL url = new URL(upLoadServerUri); 
       conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL 
       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); 

       bytesAvailable = fileInputStream.available(); // create a buffer of maximum size 

       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() { 
          tv.setText("File Upload Completed."); 
          Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show(); 
         } 
        });     
       }  

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

      } catch (MalformedURLException ex) { 
       dialog.dismiss(); 
       ex.printStackTrace(); 
       Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show(); 
       Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
      } catch (Exception e) { 
       dialog.dismiss(); 
       e.printStackTrace(); 
//    Toast.makeText(MainActivity.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
       Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
      } 
      dialog.dismis`enter code here`s();  
      return serverResponseCode; 
     } 
} 

дает следующую ошибку.

Http response is : not found: 404 
RES : 404 
skipped 119 frames! The application may be doing too many work on its main thread 
skipped 63 frames! The application may be doing too many work on its main thread 
skipped 79 frames! The application may be doing too many work on its main thread 

Может кто-нибудь скажет, что это за решение.

ответ

1

Используйте этот код ....

Его работа для меня.

Строка fileName = sourceFileUri; // Использование вашего видеофайла Путь или Uri

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 = ProgressDialog.show(CameraPhotoCapture.this, "", "Uploading file...", true); 
     dialog.dismiss(); 

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

     runOnUiThread(new Runnable() { 
      public void run() { 
       // messageText.setText("Source File not exist :"        +uploadFilePath + "" + uploadFileName); 
      } 
     }); 

     return 0; 
    } 
    else 
    { 
     try { 

      // open a URL connection to the Servlet 
      FileInputStream fileInputStream = new FileInputStream(sourceFile); 
      URL url = new URL(upLoadServerUri); 




      conn = (HttpURLConnection) url.openConnection(); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 
      conn.setUseCaches(false); 
      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){ 

       runOnUiThread(new Runnable() { 
        public void run() { 


         File se = new File(full_path_name); 

         String ser = se.getName(); 

         String string =full_path_name; 
         String[] parts = string.split("/"); 
         String part1 = parts[0]; // 004 
         String part2 = parts[1]; 
         String part3 = parts[2]; 
         String part4 = parts[3]; 
         String msg = "http://172.17.2.139/manimca/smartcomplaints/Images/"+part4; 


         // messageText.setText(msg); 
         Toast.makeText(CameraPhotoCapture.this, "File Upload Complete.", 
           Toast.LENGTH_SHORT).show(); 

. . . . .

      try 
         { 
          HttpClient httpclient = new DefaultHttpClient(); 
          HttpPost httppost = new HttpPost("http://172.17.2.139/yourpath/yourfoldername/yourphppage.php"); 
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
          HttpResponse response = httpclient.execute(httppost); 
          HttpEntity entity = response.getEntity(); 
          is = entity.getContent(); 
          Log.e("pass 1", "connection success "); 
         } 

         catch(Exception e) 
         { 
          Log.e("Fail 1", e.toString()); 
          Toast.makeText(getApplicationContext(), "Invalid IP Address", 
            Toast.LENGTH_LONG).show(); 
         }  

         try 
         { 
          BufferedReader reader = new BufferedReader 
            (new InputStreamReader(is,"iso-8859-1"),8); 
          StringBuilder sb = new StringBuilder(); 
          while ((line = reader.readLine()) != null) 
          { 
           sb.append(line + "\n"); 
          } 
          is.close(); 
          result = sb.toString(); 
          Log.e("pass 2", "connection success "); 
         } 
         catch(Exception e) 
         { 
          Log.e("Fail 2", e.toString()); 
         }  

         try 
         { 
          JSONObject json_data = new JSONObject(result); 
          code=(json_data.getInt("code")); 

          if(code==1) 
          { 
           Toast.makeText(getBaseContext(), "Inserted Successfully", 
             Toast.LENGTH_SHORT).show(); 
          } 
          else 
          { 
           Toast.makeText(getBaseContext(), "Sorry, Try Again", 
             Toast.LENGTH_LONG).show(); 
          } 
         } 
         catch(Exception e) 
         { 
          Log.e("Fail 3", e.toString()); 
         } 
        } 
       });    
      } 
      //close the streams // 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 
      finish(); 

     } catch (MalformedURLException ex) { 

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

      runOnUiThread(new Runnable() { 
       public void run() { 
        //  messageText.setText("MalformedURLException Exception : check script url."); 
        Toast.makeText(CameraPhotoCapture.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(CameraPhotoCapture.this, "No Internet Connection ", 
          Toast.LENGTH_SHORT).show(); 
       } 
      }); 
      Log.e("Upload file to server Exception", "Exception : " 
        + e.getMessage(), e); 
     } 
     dialog.dismiss();  
     return serverResponseCode; 

    } // End else block 
+0

спасибо @mani MCA Android Developer здесь вы упомянули «Строка тзд = "http://172.17.2.139/manimca/smartcomplaints/Images/"+part4;" линия.здесь что такое 172.17.2.139? – Venkatesh

Смежные вопросы