2011-07-27 23 views
4

我正在開發一個應用程序上傳視頻到Apache/PHP服務器。在這一刻我已經可以上傳視頻。我需要在文件上傳時顯示進度條。我有下一個代碼使用AsyncTask和HTTP 4.1.1庫來模擬FORM。我需要知道多少字節已經上傳更新進度條android

class uploadVideo extends AsyncTask<Void,Void,String>{ 

    @Override 
    protected String doInBackground(Void... params) { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.youtouch.cl/videoloader/index.php");   
     try { 
      // Add your data 
      File input=new File(fileName);    

      MultipartEntity multi=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);     

      multi.addPart("video", new FileBody(input));     

      httppost.setEntity(multi); 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost);    

      HttpEntity entity = response.getEntity(); 

      BufferedReader reader = new BufferedReader(
        new InputStreamReader(
          entity.getContent(), "UTF-8")); 
      String sResponse = reader.readLine(); 
      return sResponse; 

     } catch (ClientProtocolException e) { 
      Log.v("Uri Galeria", e.toString()); 
      e.printStackTrace();     

     } catch (IOException e) { 
      Log.v("Uri Galeria", e.toString()); 
      e.printStackTrace();     
     } 
     return "error"; 
    } 

    @Override 
    protected void onProgressUpdate(Void... unsued) { 
       //Here I do should update the progress bar 
    } 

    @Override 
    protected void onPostExecute(String sResponse) { 
     try { 
      if (pd.isShowing()) 
       pd.dismiss(); 

      if (sResponse != null) { 
       JSONObject JResponse = new JSONObject(sResponse); 
       int success = JResponse.getInt("SUCCESS"); 
       String message = JResponse.getString("MESSAGE"); 
       if (success == 0) { 
        Toast.makeText(getApplicationContext(), message, 
          Toast.LENGTH_LONG).show(); 
       } else { 
        Toast.makeText(getApplicationContext(), 
          "Video uploaded successfully", 
          Toast.LENGTH_SHORT).show(); 

       } 
      } 
     } catch (Exception e) { 
      Toast.makeText(getApplicationContext(), 
        e.getMessage(), 
        Toast.LENGTH_LONG).show(); 
      Log.e(e.getClass().getName(), e.getMessage(), e); 
     } 
    } 

我需要知道在哪裏我可以得到多少字節已上傳。 File.length是總大小。

回答

3

您是否試過擴展FileBody?推測POST可能會調用getInputStream()writeTo()以實際發送文件數據到服務器。您可以擴展其中的任何一個(包括由getInputStream()返回的InputStream)並跟蹤發送了多少數據。

+0

我會嘗試你的答案。問候! – ClarkXP

+0

它在post期間調用FileBody.writeTo()。 – Octavian

3

感謝cyngus的想法我解決了這個問題。我已經添加了一個代碼,用於跟蹤上傳字節:在上傳按鈕

監聽器:

btnSubir.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      //pd = ProgressDialog.show(VideoAndroidActivity.this, "", "Subiendo Video", true, false); 

      pd = new ProgressDialog(VideoAndroidActivity.this); 
      pd.setMessage("Uploading Video"); 
      pd.setIndeterminate(false); 
      pd.setMax(100); 
      pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      pd.show(); 
      //Thread thread=new Thread(new threadUploadVideo()); 
      //thread.start(); 
      new UploadVideo().execute(); 
     } 
    }); 

的AsyncTask的運行上傳:

class UploadVideo extends AsyncTask<Void,Integer,String> { 
    private FileBody fb; 

    @Override 
    protected String doInBackground(Void... params) { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.youtouch.cl/videoloader/index.php"); 
     int count; 
     try { 
      // Add your data 
      File input=new File(fileName); 

      // I created a Filebody Object 
      fb=new FileBody(input); 
      MultipartEntity multi=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
      multi.addPart("video",fb);   

      httppost.setEntity(multi);    
      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 

      //get the InputStream 
      InputStream is=fb.getInputStream(); 

      //create a buffer 
      byte data[] = new byte[1024];//1024 

      //this var updates the progress bar 
      long total=0; 
      while((count=is.read(data))!=-1){ 
       total+=count; 
       publishProgress((int)(total*100/input.length())); 
      } 
      is.close();    
      HttpEntity entity = response.getEntity(); 

      BufferedReader reader = new BufferedReader(
        new InputStreamReader(
          entity.getContent(), "UTF-8")); 
      String sResponse = reader.readLine(); 
      return sResponse; 

     } catch (ClientProtocolException e) { 
      Log.v("Uri Galeria", e.toString()); 
      e.printStackTrace();     

     } catch (IOException e) { 
      Log.v("Uri Galeria", e.toString()); 
      e.printStackTrace();     
     } 
     return "error"; 
    } 

    @Override 
    protected void onProgressUpdate(Integer... unsued) {   
     pd.setProgress(unsued[0]); 
    } 

    @Override 
    protected void onPostExecute(String sResponse) { 
     try { 
      if (pd.isShowing()) 
       pd.dismiss(); 

      if (sResponse != null) { 
        Toast.makeText(getApplicationContext(),sResponse,Toast.LENGTH_SHORT).show(); 
        Log.i("Splash", sResponse);     
      } 
     } catch (Exception e) { 
      Toast.makeText(getApplicationContext(), 
        e.getMessage(), 
        Toast.LENGTH_LONG).show(); 
      Log.e(e.getClass().getName(), e.getMessage(), e); 
     } 
    } 


} 

進度條負荷有點慢(在開始似乎凍結,然後加載1到100非常快),但工程。

對不起,我的英語是有規律:(。

+1

這不是解決方法:(因爲視頻加載與進度條進程沒有關係,這個代碼首先是視頻加載,然後是進度條,不是並行的。 – ClarkXP

+0

你是怎麼解決這個問題的? ??如果你回答,請標記我:) –

1

我用來做的是延長org.apache.http.entity.ByteArrayEntity和覆蓋諸如以下的writeTo功能,而字節輸出它會通過,雖然的writeTo (),所以你可以指望電流輸出字節:

@Override 
public void writeTo(final OutputStream outstream) throws IOException 
{ 
    if (outstream == null) { 
     throw new IllegalArgumentException("Output stream may not be null"); 
    } 

    InputStream instream = new ByteArrayInputStream(this.content); 

    try { 
     byte[] tmp = new byte[512]; 
     int total = (int) this.content.length; 
     int progress = 0; 
     int increment = 0; 
     int l; 
     int percent; 

     // read file and write to http output stream 
     while ((l = instream.read(tmp)) != -1) { 
      // check progress 
      progress = progress + l; 
      percent = Math.round(((float) progress/(float) total) * 100); 

      // if percent exceeds increment update status notification 
      // and adjust increment 
      if (percent > increment) { 
       increment += 10; 
       // update percentage here !! 
      } 

      // write to output stream 
      outstream.write(tmp, 0, l); 
     } 

     // flush output stream 
     outstream.flush(); 
    } finally { 
     // close input stream 
     instream.close(); 
    } 
}