메뉴 건너뛰기

XEDITION

ANDROID

조회 수 266 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

Any one suggest some sample to upload an video to from sdcard to remote server.

Thanks in advance.

Had the same issue some time ago. Here's a code.

public static int upLoad2Server(String sourceFileUri) {
  String upLoadServerUri = "your remote server link";
  // String [] string = sourceFileUri;
  String fileName = sourceFileUri;

  HttpURLConnection conn = null;
  DataOutputStream dos = null;
  DataInputStream inStream = null;
  String lineEnd = "\r\n";
  String twoHyphens = "--";
  String boundary = "*****";
  int bytesRead, bytesAvailable, bufferSize;
  byte[] buffer;
  int maxBufferSize = 1 * 1024 * 1024;
  String responseFromServer = "";

  File sourceFile = new File(sourceFileUri);
  if (!sourceFile.isFile()) {
   Log.e("Huzza", "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
   Log.i("Huzza", "Initial .available : " + bytesAvailable);

   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("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
   // close streams
   Log.i("Upload file to server", fileName + " File is written");
   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();
  }
//this block will give the response of upload link
  try {
   BufferedReader rd = new BufferedReader(new InputStreamReader(conn
     .getInputStream()));
   String line;
   while ((line = rd.readLine()) != null) {
    Log.i("Huzza", "RES Message: " + line);
   }
   rd.close();
  } catch (IOException ioex) {
   Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
  }
  return serverResponseCode;  // like 200 (Ok)

 } // end upLoad2Server

2)call it with

int reponse=upLoad2Server(""+filepath);

 

 

Two step solution:

1) Select the video file from the gallery.

Create a global int private static final int SELECT_VIDEO = 3; -- it doesn't matter what number you use, so long as that's to one you check for later on. Then, use an intent to select a video.

Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select a Video "), SELECT_VIDEO);

Use onActivityResult() to start the uploadVideo() method.

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {

        if (requestCode == SELECT_VIDEO)
        {
            System.out.println("SELECT_VIDEO");
            Uri selectedImageUri = data.getData();
            selectedPath = getPath(selectedImageUri);
            System.out.println("SELECT_VIDEO Path : " + selectedPath);

            uploadVideo(selectedPath);        
    }

2) Go to http://hc.apache.org/downloads.cgi, download the latest HttpClient jar, add it to your project, and upload the video using the following method:

private void uploadVideo(String videoPath) throws ParseException, IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(YOUR_URL);

    FileBody filebodyVideo = new FileBody(new File(videoPath));
    StringBody title = new StringBody("Filename: " + videoPath);
    StringBody description = new StringBody("This is a video of the agent");
    StringBody code = new StringBody(realtorCodeStr);

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("videoFile", filebodyVideo);
    reqEntity.addPart("title", title);
    reqEntity.addPart("description", description);
    reqEntity.addPart("code", code);
    httppost.setEntity(reqEntity);

    // DEBUG
    System.out.println( "executing request " + httppost.getRequestLine( ) );
    HttpResponse response = httpclient.execute( httppost );
    HttpEntity resEntity = response.getEntity( );

    // DEBUG
    System.out.println( response.getStatusLine( ) );
    if (resEntity != null) {
      System.out.println( EntityUtils.toString( resEntity ) );
    } // end if

    if (resEntity != null) {
      resEntity.consumeContent( );
    } // end if

    httpclient.getConnectionManager( ).shutdown( );
} // end of uploadVideo( )

Once you have it working you'll probably want to put it in a thread and add an uploading dialog, but this will get you started. Working for me after I unsuccessfully tried the upload2Server() method. This will also work for images and audio with some minor tweaking.

private String mString;
private Uri image_uri;  
private String response;    
private HttpURLConnection conn = null;
private DataOutputStream dos = null;
private String lineEnd = "\r\n";
private String twoHyphens = "--";
private String boundary = "*****";
private int bytesRead, bytesAvailable, bufferSize;
private byte[] buffer;
private String url_for_image_upload = "your_web_api_put_here";
private int maxBufferSize = 1 * 1024 * 1024;

//then call these two methods on button's onclick listener

mString = getRealPathFromURI(image_uri);

ImageUpload();

//write these methods here

private void ImageUpload() {

    Toast.makeText(getApplicationContext(),
            "Please Wait while uploading Image", Toast.LENGTH_SHORT).show();

    try {
        FileInputStream fileInputStream = new FileInputStream(new File(mString));
        URL url = new URL(url_for_image_upload);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);

        conn.setDoOutput(true);

        conn.setUseCaches(false);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"img_name\";filename=\"img_name"
                + "\"" + lineEnd);
        dos.writeBytes(lineEnd);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        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);
        }
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        Log.d("BuffrerReader", "" + in);

        if (in != null) {
            response = convertStreamToString(in);
            Log.e("FINAL_RESPONSE-LENGTH",""+response.length());
            Log.e("FINAL_RESPONSE", response);
        }

        fileInputStream.close();
        dos.flush();
        dos.close();

        if (response.startsWith("0")) {
            Toast.makeText(getApplicationContext(),
                    "Image Uploaded not successfully", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Image Uploaded successfully", Toast.LENGTH_SHORT)
                    .show();

        }

    } catch (MalformedURLException ex) {
        Log.e("Image upload", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Image upload", "error: " + ioe.getMessage(), ioe);
    }

}

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaColumns.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();

    mString = cursor.getString(column_index);

    return mString;

}

public static String convertStreamToString(BufferedReader is)
        throws IOException {
    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;
        try {

            while ((line = is.readLine()) != null) {
                sb.append(line).append("");
            }
        } finally {

 

 

I am making an application where i have to capture video and upload it to server like vine application.

Flow of the work: One button will be used "Upload your own video"

When user clicks on the button it will open camera and will start recording video. when user stops recording the video will save on a folder on sdcard and and automatically upload to server.

I have two test project. One capturing video and saving it. Other uploads video or any file onto server. On upload video project i have pre-assign a particular file.

My question is how to merge these two projects to accomplish my needs.

I am posting source code below:

Source code for file upload:

 //   messageText.setText("Uploading file path :- '/mnt/sdcard/"+uploadFileName+"'");

    messageText.setText("Uploading file path :- '/storage/emulated/0/"+uploadFileName+"'");

    /************* Php script path ****************/
    upLoadServerUri = "MY_SERVER_LINK";

    uploadButton.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() {
                                    messageText.setText("uploading started.....");
                                }
                            });                      

                         uploadFile(uploadFilePath + "" + uploadFileName);

                    }
                  }).start();        
            }
        });
}

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 :"
                               +uploadFilePath + "" + uploadFileName);

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

               // 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.v("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"
                                          +" MY_SERVER_LINK"
                                          +uploadFileName;

                            messageText.setText(msg);
                            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();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      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();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(MainActivity.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 

Source code for video capture:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActivityContext = this;

    Button buttonRecording = (Button)findViewById(R.id.recording);
    output = (TextView)findViewById(R.id.output);

    buttonRecording.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View arg0) {

            // create new Intentwith with Standard Intent action that can be
            // sent to have the camera application capture an video and return it. 
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

            // create a file to save the video
            fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); 

            // set the image file name  
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  

            // set the video image quality to high
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); 

            // start the Video Capture Intent
            startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

        }});
}

/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){

      return Uri.fromFile(getOutputMediaFile(type));
}

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){

    // Check that the SDCard is mounted
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_PICTURES), "MyCameraVideo");


    // Create the storage directory(MyCameraVideo) if it does not exist
    if (! mediaStorageDir.exists()){

        if (! mediaStorageDir.mkdirs()){

            output.setText("Failed to create directory MyCameraVideo.");

            Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.", 
                    Toast.LENGTH_LONG).show();

            Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
            return null;
        }
    }

In your code for video capture you have called

 startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

Merging them, add onActivityResult to the same file

  @Override

    protected void onActivityResult(int requestCode, final int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
      dialog =ProgressDialog.show(Activity.this, "", "loading...",false,true);
       if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
       //call code in upload


   runOnUiThread(new Runnable() {

                                @Override
                                public void run() {


                                    dialog.dismiss();

                                }
                            });
                            }
       }).start();
?

List of Articles
번호 제목 글쓴이 날짜 조회 수
64 [슈팅 게임 만들기] 11. 강좌가 늦어져 예제로 대신합니다 엘리후 2017.06.01 93
63 안드로이드 게임 만들기 SpriteAnimation 엘리후 2016.02.29 672
62 [안드로이드 어플 개발] 이동 애니메이션 (Translate Animation) 엘리후 2015.12.24 373
61 Multipart를 이용하여 파일+문자열 한꺼번에 전송하기 엘리후 2015.12.01 3140
60 How do I upload large files (10MB) in Android? 엘리후 2015.11.26 925
» Upload Video from android to server? 엘리후 2015.11.26 266
58 안드로이드] Fragment 쉽게 사용하기 엘리후 2015.11.24 386
57 안드로이드(android) 다이얼로그(dialog) 종류별 구현 방법 엘리후 2015.11.11 431
56 ActionBar에 메뉴 넣기. 엘리후 2015.11.11 188
55 앱 통계를 내 사이트에서 수집하기 엘리후 2015.10.07 827
54 나인패치 (9patch) 이미지 만드는 방법 엘리후 2015.10.07 350
53 VOLLEY 라이브러리 엘리후 2015.10.02 539
52 안드로이드 나인패치 이미지 만들기 [나인패치 영역선택 및 수정] 엘리후 2015.09.25 879
51 안드로이드 Support Library Setup 엘리후 2015.09.25 444
50 안드로이드 Multipart 업로드 예제 엘리후 2015.09.23 8811
49 이클립스/Eclipse 메모리 Heap 영역 늘리기 엘리후 2015.09.13 263
48 [Android, Hybrid]openFileChooser 킷캣에서 동작하지 않는 문제( openFileChooser Kitkat bug ) 엘리후 2015.08.27 605
47 Android – WebView에서 input태그를 통한 파일 업로드하기 엘리후 2015.08.27 3627
46 WebView 컨트롤 엘리후 2015.08.27 445
45 안드로이드 동영상 파일 업로드 예제 엘리후 2015.08.25 1181
44 안드로이드 채팅 ui 만들기 관련 리스트뷰(ListView)의 layout_weight 옵션을 이용한 채팅 GUI 구현, 카카오 채팅 말풍선 엘리후 2015.08.21 27790
43 Android 간단한 로그인, 회원 가입 폼 만들기 for Mac (PHPMyAdmin 이용) 엘리후 2015.08.21 1962
42 안드로이드 프레임워크 프로그래밍 [시스템서비스 추가하기] 엘리후 2015.08.11 156
41 안드로이드에서 실행 시 발생하는 에러 엘리후 2015.08.10 164
40 안드로이드 ; 스크롤 뷰 엘리후 2015.08.09 1840
39 android Facebook SDK 3.0 로그인 및 포스팅 엘리후 2015.08.07 479
38 [android] 안드로이드 전역 변수 사용하기 android global variable 엘리후 2015.07.30 645
37 [Android] WebView를 사용할때 HttpClient를 이용한 Session 유지 엘리후 2015.07.29 5567
36 [MY_SQL] where절과 having절의 차이 엘리후 2015.07.27 246
35 [안드로이드 개발 강좌] 데이터베이스(DataBase) - DB 생성,저장,수정,삭제 엘리후 2015.07.21 939
Board Pagination Prev 1 2 3 Next
/ 3
위로