2015-05-13 104 views
1

服務器,我知道如何上傳從Android的文件,我可以通過使用下面的代碼上傳大型視頻文件從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(); 
} 

代碼是可以正常使用的視頻短片,可這樣做,但它不上傳大文件,我沒有暗示爲什麼。(

我知道它的一個不好的做法,只是問爲什麼我的代碼不工作,但在這裏我問爲什麼代碼行爲不同大文件。

I al所以檢查StackOverFlow的其他答案,但沒有發現我的代碼中有任何缺陷。

感謝

+0

服務器端的任何限制? – eduyayo

+1

你有什麼錯誤,如果有的話?什麼樣的後端接收視頻? – EJTH

+0

@Syeda Zunairah你有解決方案嗎?因爲我面臨着與大視頻文件相同的問題。接受答案對你有幫助? –

回答

2

您可以嘗試HttpClient jar下載最新的HttpClient的罐子,把它添加到您的項目,並使用以下方法上傳的視頻:

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

我試過這樣的方式..但它只上傳高達1.5MB的視頻文件 –

1

嘗試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 
     } 
    }); 
1

嘗試凌空,在您的項目中添加庫,享受它的快速和易於集成。

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



}