3

我无法对此文件上传功能进行进度百分比。我google了很多我找不到解决方案

这是我的代码:

protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);

    notification.contentView.setProgressBar(R.id.progressBar, 10, progress[0], false);
    contentView.setTextViewText(R.id.text, "changed");
    mNotificationManager.notify(NOTIFICATION_ID, notification);
}

@Override
protected String doInBackground(String... urls) {

    String upLoadServerUri = upurl;
    String fileName = urls[0];
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 100 * 1024 * 1024;
    File sourceFile = new File(fileName);
    int sentBytes = 0;
    long fileSize = sourceFile.length();

     try {
            FileInputStream fileInputStream = new FileInputStream(new File(urls[0]));

            URL url = new URL(upurl);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type",     "multipart/form-data;boundary="+boundary);

            outputStream = new DataOutputStream(     connection.getOutputStream() );
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"file[]\";filename=\""+ fileName + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            Log.v("Size",bytesAvailable+"");

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                // Update progress dialog
                sentBytes += bytesRead;
                publishProgress((int)(sentBytes * 100 / fileSize));

                outputStream.write(buffer, 0, bufferSize);

                bytesAvailable = fileInputStream.available();
                Log.v("Available",bytesAvailable+"");

                bufferSize = Math.min(bytesAvailable,     maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0,      bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            Scanner s = new Scanner(connection.getInputStream());
            s.useDelimiter("\\Z");
            final String response = s.next();

            // Responses from the server (code and message)
            int serverResponseCode       = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            if(serverResponseCode == 200) {
                 runOnUiThread(new Runnable() {
                      public void run() {

                         Toast.makeText(BabupMain.this, "server say :" + response , Toast.LENGTH_SHORT).show();
                         Toast.makeText(BabupMain.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                      }
                  });
             }

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

        } catch (MalformedURLException ex) {

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(BabupMain.this, "Error 1 ", Toast.LENGTH_SHORT).show();
                }
            });

        } catch (final Exception e) {

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(BabupMain.this, "Error 2 "+ e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }

        //publishProgress();

        return null;
}
4

3 回答 3

1

真的很难说,但考虑改变

publishProgress((int)(sentBytes * 100 / fileSize))

double progress = (double)sentBytes / fileSize;
publishProgress((int)progress);

编辑

我会改变这个:

bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0)
{

      // Update progress dialog
    sentBytes += bytesRead;
    publishProgress((int)(sentBytes * 100 / fileSize));

    outputStream.write(buffer, 0, bufferSize);

    bytesAvailable = fileInputStream.available();
    Log.v("Available",bytesAvailable+"");



    bufferSize = Math.min(bytesAvailable,     maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0,      bufferSize);
}

缓冲区 = 新字节 [maxBufferSize];

while (true)
{
    int bytesToRead = Math.min(maxBufferSize, fileInputStream.available());

    // Break if complete
    if(bytesToRead == 0){ break; }

    // Read bytes
    bytesRead = fileInputStream.read(buffer, 0, bytesToRead);

    // Write bytes
    outputStream.write(buffer, 0, bytesRead);

    // Update progress dialog
    sentBytes += bytesRead;

    // Publish progress
    double progress = (double)sentBytes / fileSize;
    publishProgress((int)progress);
}

如果您对此有疑问,我会放弃该FileInputStream.available()方法,获取字节总数File.length()并在bytesRead >= File.length().

于 2013-04-01T17:30:27.720 回答
0

这里有一个简单而好的解决方案:https ://developer.android.com/reference/java/net/HttpURLConnection.html在“发布内容”部分:

添加:

connection.setChunkedStreamingMode(0);

刚过:

connection.setDoOutput(true);
于 2016-09-24T03:40:48.453 回答
0

只看了一眼……

  1. sentBytes * 100 / 文件大小

    int sentBytes = 0;
    长文件大小 = sourceFile.length();

    请注意,使用 int 和 long 进行计算会在小数点处转换。也许投加倍。

  2. 第二个我因为缺少代码而看不到,但评论为它尖叫

    但是通知变得粘滞并且手机冻结

    您在后台线程(doInBackground())中使用 publishProgress(),我希望您不要在后台线程中尝试触摸 GUI

    您可以使用 Handler() 发布将由 gui 线程使用的 Runnable

于 2016-06-10T12:13:11.637 回答