每秒上传进度 - Android

时间:2017-02-23 17:07:30

标签: java android file-upload server

我正在尝试上传服务器上的文件,并以这种方式显示每秒上传的字节数:

public void RunUploadTest () {
    try {
        URL url = new URL(serverLink);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("content-type", "video/mp4");

        for(int i =0; i<10; i++) {
            FileInputStream fis = new FileInputStream(myFileVideo);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            int bytesWrite = 0;
            byte[] buffer = new byte[512];
            Stopwatch timer = new Stopwatch();
            int read;
            while ((read = fis.read(buffer)) != -1&& timer.elapsedTime()<1000) {
                dos.write(buffer, 0, read);
                dos.flush();
                bytesWrite++;
            }
            Log.d("Upload", "Bytes written: " + bytesWrite*512);
        }
        fis.close();

    } catch (IOException e){
        e.printStackTrace();
    }
}

问题在于不计算我预期上传的字节数。 你知道为什么不工作吗?

1 个答案:

答案 0 :(得分:1)

如果您写入的字节数相同10倍,则有2个选项:

  1. 您的文件写入时间不到1秒;
  2. 您的elapsedTime方法,以秒为单位返回(例如),而不是以毫秒为单位
  3. 你可能也不需要for循环,它会让你读取文件10次。

    我会像这样重写你的代码:

    public void RunUploadTest () {
        try {
            URL url = new URL(serverLink);
    
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "video/mp4");
    
            FileInputStream fis = new FileInputStream(myFileVideo);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            int bytesWrite = 0;
            byte[] buffer = new byte[512];
            int read;
            while((read = fis.read(buffer))) {
                Stopwatch timer = new Stopwatch();
                while (timer.elapsedTime()<1) { //my guess here is that this method returns in seconds
                    dos.write(buffer, 0, read);
                    dos.flush();
                    bytesWrite += read; //taken from Yoni Gross answer
                }
                Log.d("Upload", "Bytes written: " + bytesWrite);
            }
            fis.close();
    
        } catch (IOException e){
            e.printStackTrace();
        }
    }