2012-03-14 83 views
1

以下代码以百分比方式将文件上载到服务器显示progressdialog,没有任何问题。使用Apache API在Android中使用文件上传显示进度百分比

protected boolean uploadFile(String serverUrl, String filePath) { 
      HttpURLConnection connection = null; 
      DataOutputStream outputStream = null; 
      DataInputStream inputStream = null; 
      int bytesRead, bytesAvailable, bufferSize; 
      byte[] buffer; 
      int serverResponseCode; 
      String serverResponseMessage; 
      boolean uploadstatus = false; 
      int count; 
      long lengthOfFile; 

      try { 
       urlServer = serverUrl; 
       pathFile = filePath; 

       FileInputStream fileInputStream; 
       fileInputStream = new FileInputStream(new File(pathFile)); 
       URL url = new URL(urlServer); 
       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(lineEnd); 
       lengthOfFile = new File(filePath).length();// length of file 
       bytesAvailable = fileInputStream.available(); 
       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       buffer = new byte[1024]; 
       bytesRead = 0; 
       String progressMsg = ""; 
       while ((bytesRead = fileInputStream.read(buffer)) != -1) { 
        total += bytesRead; 
        progressMsg = new StringBuffer(" ").append((int) ((total * 100)/totalLengthOfFile)).toString(); 
        prgressBarMsg[0] = progressMsg; 
        publishProgress(prgressBarMsg); 
        outputStream.write(buffer);// , 0, bufferSize); 
       } 
       outputStream.writeBytes(lineEnd); 
       outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
       // Responses from the server (code and message) 
       serverResponseCode = connection.getResponseCode(); 
       serverResponseMessage = connection.getResponseMessage(); 
       if (serverResponseCode == 200)// HTTP OK Message from server 
       { 
        uploadstatus = true; 
       } else { 
        uploadstatus = false; 
       } 
       // this block will give the response of upload link 
       try { 
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
        String line; 
        while ((line = rd.readLine()) != null) { 
         // Log.i("ARC", "RES Message: " + line); 
        } 
        rd.close(); 
       } catch (IOException ioex) { 
        // Log.e("ARC", "error: " + ioex.getMessage(), ioex); 
       } 
       fileInputStream.close(); 
       outputStream.flush(); 
       outputStream.close(); 
      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (ProtocolException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } finally { 
       connection.disconnect(); 
      } 
      return uploadstatus; 
     } 

使用Apache还上传文件到服务器&下面的代码被推荐用于上传文件与较大尺寸(它是更稳定的),但它是在上载所用的时间方面有点慢相比上述代码。当文件大小超过20 MB时,我发现使用HttpURLConnection的代码抛出异常,所以现在我正在使用Apache实现文件上传代码。

protected boolean uploadFile(String serverUrl, String filePath) { 
     boolean status = false; 
     try { 
      File file = new File(filePath); 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost postRequest = new HttpPost(serverUrl); 
      FileBody bin = new FileBody(file); 
      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT); 
      reqEntity.addPart("myfile", bin); 
      postRequest.setEntity(reqEntity); 
      HttpResponse response = httpClient.execute(postRequest); 
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
       String sResponse; 
       StringBuilder responseMsg = new StringBuilder(); 
       while ((sResponse = reader.readLine()) != null) { 
        responseMsg = responseMsg.append(sResponse); 
       } 
      } 
      status = true; 
     } catch (ClientProtocolException e) { 
     } catch (IOException e) { 
     } 
     return status; 
    } 

我想使用Apache代码显示文件上传百分比的progressdialog。 我们如何获得用于计算Apache代码的progressdialog百分比的bytesRead值?

任何建议/提示实施相同将帮助。

+0

已经[回答](http://stackoverflow.com/a/470047/165674)已经。 – 2012-03-24 16:41:26

+0

@chiranjib我已经看到所有的答案,但没有得到工作。你可以在你的答案中上传完整的代码吗? – 2013-10-28 06:39:52

回答

相关问题