简体   繁体   English

从Android将大型视频文件上传到服务器

[英]Upload Large Video files to the server from android

I know how to upload the file from android and I am able to do it by using the following code 我知道如何从android上传文件,并且可以通过使用以下代码来做到这一点

private void doFileUpload(MessageModel model) {
    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;// 1 MB
    String responseFromServer = "";

    String imageName = null;
    try {
        // ------------------ CLIENT REQUEST
        File file = new File(model.getMessage());
        FileInputStream fileInputStream = new FileInputStream(file);
        AppLog.Log(TAG, "File Name :: " + file.getName());
        String[] temp = file.getName().split("\\.");
        AppLog.Log(TAG, "temp array ::" + temp);
        String extension = temp[temp.length - 1];
        imageName = model.getUserID() + "_" + System.currentTimeMillis()
                + "." + extension;

        // open a URL connection to the Servlet
        URL url = new URL(Urls.UPLOAD_VIDEO);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        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=\"uploaded_file\";filename=\""
                + imageName + "\"" + lineEnd);
        Log.i(TAG, "Uploading starts");
        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) {
            // Log.i(TAG, "Uploading");
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            AppLog.Log(TAG, "Uploading Vedio :: " + imageName);
        }
        // send multipart form data necesssary after file data...

        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // close streams
        Log.e("Debug", "File is written");
        Log.i(TAG, "Uploading ends");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    // ------------------ read the SERVER RESPONSE ----------------
    try {
        inStream = new DataInputStream(conn.getInputStream());
        String str;

        while ((str = inStream.readLine()) != null) {
            Log.e("Debug", "Server Response " + str);
            try {
                final JSONObject jsonObject = new JSONObject(str);
                if (jsonObject.getBoolean("success")) {
                    handler.post(new Runnable() {
                        public void run() {
                            try {
                                Toast.makeText(getApplicationContext(),
                                        jsonObject.getString("message"),
                                        Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Toast.makeText(getApplicationContext(),
                                        jsonObject.getString("message"),
                                        Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        model.setMessage(imageName);
        onUploadComplete(model);
        inStream.close();

    } catch (IOException ioex) {
        ioex.printStackTrace();
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
    manageQueue();
}

the code is working perfectly for short videos but it is not uploading the large files and I no hint why .:( 该代码对于短视频来说是完美的,但是不能上传大文件 ,我也没有暗示为什么。:(

I know its a bad practice to just ask that why my code is not working but here I am asking why is the code behaving different for large files. 我只问我的代码为什么不起作用是一种不好的做法,但是在这里我问为什么大型文件的代码表现出不同。

I also check other answers on StackOverFlow but didn't find any flaw in my code. 我还检查了StackOverFlow上的其他答案,但未在我的代码中发现任何缺陷。

Thanks 谢谢

You can try HttpClient jar download the latest HttpClient jar, add it to your project, and upload the video using the following method: 您可以尝试使用HttpClient jar下载最新的HttpClient jar,将其添加到您的项目中,然后使用以下方法上传视频:

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

Try Android Asynchronous Http Client library. 尝试使用Android异步Http客户端库。

  AsyncHttpClient client = new AsyncHttpClient();
    File myFile = new File("/path/to/video");
    RequestParams params = new RequestParams();
    try {
        params.put("video", myFile);
    }  catch(FileNotFoundException e) {}
    client.post("POST URL",params, new AsyncHttpResponseHandler() {

        @Override
        public void onStart() {
            // called before request is started
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            // called when response HTTP status is "200 OK"
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        }

        @Override
        public void onRetry(int retryNo) {
            // called when request is retried
        }
    });

Try volley, add library in your project and enjoy, its fast and easy to integrate. 尝试排球,在您的项目中添加库,并享受它的快速和轻松集成。

final AbstractUploadServiceReceiver uploadReceiver = new AbstractUploadServiceReceiver() {

                            @Override
                            public void onProgress(String uploadId, int progress) {

                                Log.i("", "upload with ID " + uploadId + " is: " + progress);
                            }

                            @Override
                            public void onError(String uploadId, Exception exception) {


                                String message = "Error in upload with ID: " + uploadId + ". " + exception.getLocalizedMessage();
                                Log.e("", message, exception);
                            }

                            @Override
                            public void onCompleted(String uploadId, int serverResponseCode, String serverResponseMessage) {

                                String message = "Upload with ID " + uploadId + " is completed: " + serverResponseCode + ", "
                                        + serverResponseMessage;
                                Log.i("", message);
                            }
                        };

                        uploadReceiver.register(context);

                    final docUploadParams item="yourdocUploadParam";

                    sendUploaderRequest(context, URLtoUpload, item);







public void sendUploaderRequest(Context context,String url,docUploadParams item)
{
final UploadRequest request = new UploadRequest(context,url);             
//in case of image
    request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile(  ).getName() , ContentType.IMAGE_JPEG);
//in case of audio              
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile().getName() , ContentType.AUDIO_M3U);
//in case of video
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile().getName() , ContentType.VIDEO_MPEG);
//custom parameters if any
request.addParameter("userId",item.userID);

//progress on notification bar        
request.setNotificationConfig(R.drawable.ic_launcher,
                "Uploading Files",
                "Upload in Progress",
                "Upload Completed Successfully",
                "Error in Uploading",
                false);


        try {
            UploadService.startUpload(request);
        } catch (Exception exc) {  
           exc.printStackTrace();
        }



}

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

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