【问题标题】:Upload Large Video files to the server from android从 android 上传大视频文件到服务器
【发布时间】:2015-05-13 08:39:41
【问题描述】:

我知道如何从 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();
}

该代码非常适合短视频,但无法上传大文件,我不知道为什么。:(

我知道只问我的代码为什么不起作用是一种不好的做法,但在这里我要问的是为什么代码对于大文件的行为不同。

我还在 * 上查看了其他答案,但没有发现我的代码有任何缺陷。

谢谢

【问题讨论】:

  • 服务器端有什么限制吗?
  • 你会得到什么错误,如果有的话?什么样的后端接收视频?
  • @Syeda Zunairah 你有解决方案吗?因为我面临与大视频文件相同的问题。接受的答案对您有帮助吗??
  • @BhoomikaPatel 是的。
  • 其实也要看服务端api是怎么实现的。

标签: php android file-upload


【解决方案1】:

您可以尝试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( )

【讨论】:

  • 我试过这样。但它最多只能上传 1.5MB 的视频文件
【解决方案2】:

试试Android Asynchronous Http Client库。

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

【讨论】:

    【解决方案3】:

    尝试 volley,在您的项目中添加库并享受它,它快速且易于集成。

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

    【讨论】: