DeepSidhu1313
DeepSidhu1313

Reputation: 805

Get Progress in %age with upload speed while uploading file over http using Java?

I was working on some code to upload files on http url. But i don't know how to get %age & upload speed while transfering to make it more verbose.

httpupload.java

   import java.io.File;
   import java.io.IOException;
   import java.io.InputStream;
   import java.io.RandomAccessFile;
   import java.io.StringWriter;
   import java.io.UnsupportedEncodingException;
   import java.text.DecimalFormat;

   import javax.xml.ws.spi.http.HttpContext;

   import org.apache.http.HttpEntity;
   import org.apache.http.HttpResponse;
   import org.apache.http.HttpVersion;
   import org.apache.http.client.HttpClient;
   import org.apache.http.client.methods.HttpPost;
   import org.apache.http.client.methods.HttpPut;
   import org.apache.http.entity.mime.MultipartEntity;
   import org.apache.http.entity.mime.content.FileBody;
   import org.apache.http.impl.client.DefaultHttpClient;
   import org.apache.http.params.BasicHttpParams;
   import org.apache.http.params.HttpParams;
   import org.apache.http.params.HttpProtocolParams;
   import org.apache.http.protocol.BasicHttpContext;

   public class httpupload  {
String str;
private int transferedMegaBytes = 0;
int choice;
long size = 0;
static int iter;
DecimalFormat df = new DecimalFormat("#.00");
RandomAccessFile f1;
httpUploadProgress fileEntity;

boolean bo1, bo2, bo3, bo4;// truefalsetruefalse

public httpupload(boolean b1, boolean b2, boolean b3, boolean b4,
        int Iterations) {
    super();

    // TODO Auto-generated constructor stub
    bo1 = b1;
    bo2 = b2;
    bo3 = b3;
    bo4 = b4;
    this.iter = Iterations;
    if(bo1){
        ProgressBar.maxprogress+= iter*250*1024;
    }
    if(bo2){
        ProgressBar.maxprogress+=iter*500*1024;
    }
    if(bo3){
        ProgressBar.maxprogress+=iter*2*1024*1024;
    }
    if(bo4){
        ProgressBar.maxprogress+=iter*10*1024*1024;
    }

    try {
        ProgressBar.status="Uploading File via HTTP";
        this.chooseFiles(bo1, bo2, bo3, bo4);
        //System.out.println(httpUploadProgress.getSpeed());
    } catch (Exception ex) {
        //System.out.println(ex.getLocalizedMessage());
    }   
}

public void chooseFiles(boolean b1, boolean b2, boolean b3, boolean b4)
        throws Exception {
    for (int i = 0; i < iter; i++) {
        if (b1) {
            ProgressBar.status="Uploading File Of Size 250KB";
            this.startUpload(1);
        }
        if (b2) {
            ProgressBar.status="Uploading File Of Size 500KB";
            this.startUpload(2);
        }
        if (b3) {
            ProgressBar.status="Uploading File Of Size 2MB";
            this.startUpload(3);
        }
        if (b4) {
            ProgressBar.status="Uploading File Of Size 10MB";
            //this.post();
            this.startUpload(4);
        }
    }
    httpUploadProgress.totalSpeed /= iter;
}

public static void main(String args[]) {
    httpupload av = new httpupload(false, false, false, true, 2);

}

private void startUpload(int choice) throws Exception {
    String str = "";
    switch (choice) {
    case 1:
        str = "250kb.txt";
        size = 250 * 1024;
        break;
    case 2:
        str = "500kb.txt";
        size = 500 * 1024;
        break;
    case 3:
        str = "2MB.txt";
        size = 2 * 1024 * 1024;
        break;
    case 4:
        str = "10MB.txt";
        size = 10 * 1024 * 1024;
        break;
    }

    //str="/sdcard/"+str;
    f1 = new RandomAccessFile(str, "rw");
    f1.setLength(size);
    File file = new File(str);

    String serverResponse = null;
    HttpParams params = new BasicHttpParams();
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);
    HttpPut put = new HttpPut("URL"
            + file.getName());
    //HttpPost httpPost = new HttpPost("URL");

    fileEntity = new httpUploadProgress(file, "binary/octet-stream");
    put.setEntity(fileEntity);
    //httpPost.setEntity(fileEntity);
    HttpResponse response = client.execute(put);
    //HttpResponse response = client.execute(httpPost);

    // HttpEntity entity = response.getEntity();
    /*
     * if (entity != null) { serverResponse = EntityUtils.toString(entity);
     * //System.out.println(serverResponse); }
     */

    File f2 = new File(str);
    f2.delete();

}

httpuploadProgress.java

        import java.io.File;
         import java.io.FileInputStream;
         import java.io.IOException;
         import java.io.InputStream;
         import java.io.OutputStream;
         import java.text.DecimalFormat;

         import org.apache.http.entity.AbstractHttpEntity;

        /**
        * File entity which supports a progress bar.<br/>
        * Based on "org.apache.http.entity.FileEntity".
        * @author Benny Neugebauer (www.bennyn.de)
        */
        public class httpUploadProgress extends AbstractHttpEntity implements Cloneable
        {

  protected final File file;
 // private final ProgressBarListener listener;
  private long transferredBytes;
  private long transferedMegaBytes = 0;
  long startTime, endTime,totalTime;
  static double speed,totalSpeed;
  static DecimalFormat df = new DecimalFormat("#.00");
  int choice;
  static String metrics;

  public httpUploadProgress(final File file, final String contentType)
  {
    super();
    if (file == null)
    {
      throw new IllegalArgumentException("File may not be null");
    }
    this.file = file;
    this.transferredBytes = 0;
    setContentType(contentType);
  }

  public boolean isRepeatable()
  {
    return true;
  }

  public long getContentLength()
  {
    return this.file.length();
  }

  public InputStream getContent() throws IOException
  {
    return new FileInputStream(this.file);
  }

  public void writeTo(final OutputStream outstream) throws IOException
  {
    if (outstream == null)
    {
      throw new IllegalArgumentException("Output stream may not be null");
    }
    InputStream instream = new FileInputStream(this.file);
    try
    {

        {
        byte[] tmp = new byte[1024];
      int l;
       startTime = System.nanoTime();

      while ((l = instream.read(tmp)) != -1)
      {
        outstream.write(tmp, 0, l);
        this.transferredBytes += l;

        updateTransferred(this.transferredBytes);
      }
      outstream.flush();
      endTime = System.nanoTime();
        System.out.println("End Time of "+"is :"+endTime);
        totalTime = (endTime - startTime)/1000000000;
        speed=(double)(transferredBytes/totalTime);
        System.out.println("Bytes is :"+transferredBytes);
        totalSpeed+=speed;
        System.out.println("Speed is :"+totalSpeed);
        }

    }
    finally
    {
      instream.close();
    }
  }


  public void updateTransferred(long transferedBytes)
  {
    transferedMegaBytes =  (transferedBytes/(1024*1024) );
    ProgressBar.status="Uploading File";
    System.out.println("Transferred: " + transferedMegaBytes + " Megabytes.");
  ProgressBar.progress+=(int)transferedBytes;
  }


  public String getResult(int i) throws NumberFormatException, IOException{

        choice=i;
        switch(choice)
        {
            case 1://System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 2:httpUploadProgress.totalSpeed/=1024;
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 3:httpUploadProgress.totalSpeed/=(1024*1024);
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 4:httpUploadProgress.totalSpeed/=(1024*1024*1024);
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
        }

        return df.format(httpUploadProgress.totalSpeed);
  }
  public static String getSpeedbps(){

      return    df.format(totalSpeed);
      }

  public static String getSpeedkbps(){
      return df.format(totalSpeed/=1024);

  }
      public static String getSpeedmbps(){

      return    df.format(totalSpeed/=(1024*1024));
      }
      public static String getSpeedgbps(){

      return    df.format(totalSpeed/=(1024*1024*1024));
      }

  public boolean isStreaming()
  {
    return false;
  }
  public static String getSpeed(){
    String str2 = "";
    if((totalSpeed<=1024)){
        str2=""+getSpeedbps();
        metrics=" Bps";
    }else if((totalSpeed>=1024)&& ((totalSpeed<(1024*1024 )))){

        str2=""+getSpeedkbps();
        metrics=" KBps";
    }else if((totalSpeed>=1024*1024)&& ((totalSpeed<(1024*1024*1024 )))){

        str2=""+getSpeedmbps();
        metrics=" MBps";
    }else if((totalSpeed>=1024*1024*1024 )){

        str2=""+getSpeedgbps();
        metrics=" GBps";
    }
    return str2;
  }

  public static String showSpeed(){
        String temp=""+getSpeed()+" "+getMetrics();
        return temp;
    }

    public static String getMetrics(){
        return metrics;
    }
  @Override
  public Object clone() throws CloneNotSupportedException
  {
    return super.clone();
  }
}

Some of the code also get deprecated. I don't know how to upload files using latest apache httpclient? I'm working on my study project, So it's a request to help with this problem. I'm newbie in JAVA.

Thanks

Upvotes: 0

Views: 1007

Answers (1)

SCI
SCI

Reputation: 555

Seems there is already an answer to this question at file-upload-with-java-with-progress-bar

Mainly HttpClient uses somewhere an outputstream to send the Data to the target. This outputstream has to be wrapped by you to count how many bytes already have been sent/processed.

Also knowing the full filesize by file.size() you should be able to show a percentage.

With the help of a second thread you can monitor the time passed by and determine the bytes/sec.

Upvotes: 2

Related Questions