开发者

Upload video from Android to server?

开发者 https://www.devze.com 2023-02-11 07:44 出处:网络
Anyone suggest some sample to upload a video from the SD开发者_开发技巧 card to a remote server?Had the same issue some time ago. Here\'s a code.

Anyone suggest some sample to upload a video from the SD开发者_开发技巧 card to a remote server?


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.


Create package "DocUpload"

Add 2 classes FilePath.java and SingleUploadBroadcastReceiver.java

FilePath.java ----------------------------------------

    public class FilePath
    {


        /**
         * Method for return file path of Gallery image
         *
         * @param context
         * @param uri
         * @return path of the selected image file from gallery
         */
        public static String getPath(final Context context, final Uri uri)
        {

            //check here to KITKAT or new version
            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }



                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {

                    String fileName = getFilePath(context, uri);
                    if (fileName != null) {
                        return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
                    }

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                    return getDataColumn(context, contentUri, null, null);

                    /*
                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);*/
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[] {
                            split[1]
                    };

                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {

                // Return the remote address
                if (isGooglePhotosUri(uri))
                    return uri.getLastPathSegment();

                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }

            return null;
        }


        public static String getFilePath(Context context, Uri uri) {

            Cursor cursor = null;
            final String[] projection = {
                    MediaStore.MediaColumns.DISPLAY_NAME
            };

            try {
                cursor = context.getContentResolver().query(uri, projection, null, null,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
                    return cursor.getString(index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }


        /**
         * Get the value of the data column for this Uri. This is useful for
         * MediaStore Uris, and other file-based ContentProviders.
         *
         * @param context The context.
         * @param uri The Uri to query.
         * @param selection (Optional) Filter used in the query.
         * @param selectionArgs (Optional) Selection arguments used in the query.
         * @return The value of the _data column, which is typically a file path.
         */
        public static String getDataColumn(Context context, Uri uri, String selection,
                                           String[] selectionArgs) {

            Cursor cursor = null;
            final String column = "_data";
            final String[] projection = {
                    column
            };

            try {
                Log.e("check","===========>"+uri);
               /* if (uri.toString().trim().contains("downloads/public_downloads")) {
                    uri = Uri.parse(uri.toString().replace("downloads/public_downloads", "downloads/my_downloads"));
                }
    */
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is ExternalStorageProvider.
         */
        public static boolean isExternalStorageDocument(Uri uri) {
            return "com.android.externalstorage.documents".equals(uri.getAuthority());
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is DownloadsProvider.
         */
        public static boolean isDownloadsDocument(Uri uri) {
            return "com.android.providers.downloads.documents".equals(uri.getAuthority());
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is MediaProvider.
         */
        public static boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is Google Photos.
         */
        public static boolean isGooglePhotosUri(Uri uri) {
            return "com.google.android.apps.photos.content".equals(uri.getAuthority());
        }
    }

SingleUploadBroadcastReceiver.java


public class SingleUploadBroadcastReceiver extends UploadServiceBroadcastReceiver {

    public interface Delegate {
        void onProgress(int progress);
        void onProgress(long uploadedBytes, long totalBytes);
        void onError(Exception exception);
        void onCompleted(int serverResponseCode, byte[] serverResponseBody);
        void onCancelled();
    }

    private String mUploadID;
    private Delegate mDelegate;

    public void setUploadID(String uploadID) {
        mUploadID = uploadID;
    }

    public void setDelegate(Delegate delegate) {
        mDelegate = delegate;
    }

    @Override
    public void onProgress(String uploadId, int progress) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onProgress(progress);
        }
    }

    @Override
    public void onProgress(String uploadId, long uploadedBytes, long totalBytes) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onProgress(uploadedBytes, totalBytes);
        }
    }

    @Override
    public void onError(String uploadId, Exception exception) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onError(exception);
        }
    }

    @Override
    public void onCompleted(String uploadId, int serverResponseCode, byte[] serverResponseBody) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onCompleted(serverResponseCode, serverResponseBody);
        }
    }

    @Override
    public void onCancelled(String uploadId) {
        if (uploadId.equals(mUploadID) && mDelegate != null) {
            mDelegate.onCancelled();
        }
    }
}

Implement to fragment

    implements View.OnClickListener, SingleUploadBroadcastReceiver.Delegate 

private final SingleUploadBroadcastReceiver uploadReceiver =
            new SingleUploadBroadcastReceiver();

add variables

//------------------------------------------------------------------------------------------------------------------

//Image request code
private int PICK_DOC_REQUEST = 1;
private int PICK_VIDEO_REQUEST = 2;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Uri to store the image uri
private Uri filePath = null, VideofilePath = null;


//------------------------------------------------------------------------------------------------------------------

if doc type------------- use showFileChooser(); on button click else if u need only video upload use showVideoFileChooser(); on button click

    //method to show file chooser
    private void showFileChooser() {
        // Intent intent = new Intent();
        // intent.setType("*/*");
        //   intent.setAction(Intent.ACTION_GET_CONTENT);
        //  startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_DOC_REQUEST);

        String[] mimeTypes = {"application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"};

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
            if (mimeTypes.length > 0) {
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
            }
        } else {
            String mimeTypesStr = "";

            for (String mimeType : mimeTypes) {
                mimeTypesStr += mimeType + "|";
            }

            intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
        }
        startActivityForResult(Intent.createChooser(intent, ""), PICK_DOC_REQUEST);


    }

    //method to show file chooser
    private void showVideoFileChooser() {
        // Intent intent = new Intent();
        // intent.setType("*/*");
        //   intent.setAction(Intent.ACTION_GET_CONTENT);
        //  startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_DOC_REQUEST);

        String[] mimeTypes = {"video/*"};

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
            if (mimeTypes.length > 0) {
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
            }
        } else {
            String mimeTypesStr = "";

            for (String mimeType : mimeTypes) {
                mimeTypesStr += mimeType + "|";
            }

            intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
        }
        startActivityForResult(Intent.createChooser(intent, ""), PICK_VIDEO_REQUEST);


    }

    //handling the ima chooser activity result
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_DOC_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            String filename = "DOC_" + filePath.toString().substring(filePath.toString().lastIndexOf("/") + 1);
            edtTeacherRegUploadDocument.setText(filename);
        } else if (requestCode == PICK_VIDEO_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            VideofilePath = data.getData();
            String filename = "VID_" + VideofilePath.toString().substring(VideofilePath.toString().lastIndexOf("/") + 1);
            edtUploadVideo.setText(filename);

        }
    }


    @Override
    public void onClick(View view) {

    }

    @Override
    public void onResume() {
        super.onResume();
        uploadReceiver.register(getActivity());
    }

    @Override
    public void onPause() {
        super.onPause();
        uploadReceiver.unregister(getActivity());
    }


    @Override
    public void onProgress(int progress) {

        Log.e("progress", "progress " + progress);
    }

    @Override
    public void onProgress(long uploadedBytes, long totalBytes) {
        Log.e("uploadedBytes", "uploadedBytes " + uploadedBytes);
        Log.e("totalBytes", "totalBytes " + totalBytes);
    }

    @Override
    public void onError(Exception exception) {
        Toast.makeText(getActivity(), "" + exception.toString(), Toast.LENGTH_SHORT).show();
        Log.e("exception", "exception " + exception.toString());
    }

    @Override
    public void onCompleted(int serverResponseCode, byte[] serverResponseBody) {
        Log.e("serverResponseCode", "serverResponseCode " + serverResponseCode);
        try {
            String str = new String(serverResponseBody, "UTF-8");
            Log.e("serverResponseBody", "serverResponseBody[] " + str);
            // Toast.makeText(getActivity(), "" + str, Toast.LENGTH_SHORT).show();
            //txt_error.setText(str);

            try {
                JSONObject jsonObject = new JSONObject(str);

                String error_code = jsonObject.getString("error_code");


                if (error_code.equalsIgnoreCase("1")) {

                    UtilityMethods.showSuccessToast(getActivity(), "Teacher registered successfully");

                    TeacherLoginFragment teacherLoginFragment = new TeacherLoginFragment();
                    Constants.mMainActivity.changeFragment(teacherLoginFragment, "TeacherLoginFragment");

                } else if (error_code.equalsIgnoreCase("2")) {

                    UtilityMethods.tuchOn(relativeLayoutProgressBarTeacherRegistration);
                    UtilityMethods.showWarningToast(getActivity(), "Teacher already registered");

                } else if (error_code.equalsIgnoreCase("3")) {
                } else if (error_code.equalsIgnoreCase("4")) {
                } else if (error_code.equalsIgnoreCase("5")) {
                } else if (error_code.equalsIgnoreCase("10")) {

                    UtilityMethods.showErrorToast(getActivity(), "Something went wrong, please contact to admin");

                } else if (error_code.equalsIgnoreCase("0")) {

                    UtilityMethods.showInfoToast(getActivity(), "Please enter all details");

                }


            } catch (Exception e) {
                e.printStackTrace();
                UtilityMethods.showToast(getActivity(), "Server Error");

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCancelled() {
        Log.e("onCancelled", "onCancelled ");
    }


These are the global variables to define first:

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() method

mString = getRealPathFromURI(image_uri);

ImageUpload();

//and write these methods as follows

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 {
            is.close();
        }
        return sb.toString();
    } else {
        return "";
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消