在android上传进度条?

时间:2011-02-24 10:29:16

标签: android android-layout

我使用以下代码将视频上传到php服务器,它工作正常,但我需要在文件上传时显示进度条,我需要在文件上传和进度条增量之间进行同步。任何人建议一些想法?

      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;
      String responseFromServer = "";

      File sourceFile = new File(sourceFileUri);
      if (!sourceFile.isFile()) {
       Log.e("Huzza", "Source File Does not exist");
       return;
      }
      int serverResponseCode=0;
    try { // open a URL connection to the Servlet
       FileInputStream fileInputStream = new FileInputStream(sourceFile);
       URL url = new URL(upLoadServerUri);
       conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
       conn.setDoInput(true); // Allow Inputs
       conn.setDoOutput(true); // Allow Outputs
       conn.setUseCaches(false); // Don't use a Cached Copy
       conn.setRequestMethod("POST");
       conn.setRequestProperty("Connection", "Keep-Alive");
       conn.setRequestProperty("ENCTYPE", "multipart/form-data");
       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
       conn.setRequestProperty("uploadedfile", fileName);

      // conn.setFixedLengthStreamingMode(1024);
       //conn.setChunkedStreamingMode(1);
       dos = new DataOutputStream(conn.getOutputStream());

       dos.writeBytes(twoHyphens + boundary + lineEnd);
       dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""+ fileName + "\"" + lineEnd);
       dos.writeBytes(lineEnd);

       bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
       Log.i("Huzza", "Initial .available : " + bytesAvailable);

       //bufferSize = Math.min(bytesAvailable, maxBufferSize);
       bufferSize=(int)sourceFile.length();


       System.out.println("BytesAvail"+bytesAvailable);
       System.out.println("maxBufferSize"+maxBufferSize);
       buffer = new byte[bufferSize];

       // read file and write it into form...
       bytesRead = fileInputStream.read(buffer, 0, bufferSize);

       while (bytesRead > 0) {
        dos.write(buffer, 0, bufferSize);

         bytesAvailable = fileInputStream.available();

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

       // send multipart form data necesssary after file data...
       dos.writeBytes(lineEnd);
       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

       Log.i("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
       // close streams
       Log.i("Upload file to server", fileName + " File is written");
       fileInputStream.close();
       dos.flush();
       dos.close();
      } catch (MalformedURLException ex) {
       ex.printStackTrace();
       Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
      } catch (Exception e) {
       e.printStackTrace();
      }
    //this block will give the response of upload link
      try {
       BufferedReader rd = new BufferedReader(new InputStreamReader(conn
         .getInputStream()));
       String line;
       while ((line = rd.readLine()) != null) {
        Log.i("Huzza", "RES Message: " + line);
       }
       rd.close();
      } catch (IOException ioex) {
       Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
      }
      return;  // like 200 (Ok) 

谢谢。

4 个答案:

答案 0 :(得分:7)

将您的上传代码放在doInBackGround的{​​{1}}方法中。然后,您可以AsyncTask从那里publishProgress更新ProgressBar。

onProgressUpdatepublishProgress的看法有look here

答案 1 :(得分:1)

我想您正在询问如何获取当前上传进度的数字表示,以便您可以将该值显示为进度条。使用您当前的代码,我不确定您是否可以轻松实现。您尝试上传的最大文件是什么?我认为大文件会出现OutOfMemory错误。你这样做:

byte[] buffer;
bufferSize=(int)sourceFile.length();
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
...

您的“缓冲区”只是一个与整个文件大小相同的数组。对fileInputStream.read()的调用可能会尝试将文件的完整内容放入“缓冲区”。如果您的文件很大(超过几十兆字节),那么您的应用可能会因OutOfMemory错误而崩溃。

如果您使用固定大小的小缓冲区,那么每次通过while循环,您都可以计算已发送的数据量,将其转换为百分比值并调用{{1} } publishProgessAsyncTask sendMessage

答案 2 :(得分:0)

或者你可以使用一个带有处理程序的线程,如果你想要更细粒度的控制,但对于大多数任务,AFAIK AsyncTask应该可以工作。

答案 3 :(得分:-1)

connection.setFixedLengthStreamingMode((int) requestLength);

为我做了诀窍!