android - 使用 Apache API 在 Android 中显示文件上传进度百分比

标签 android file-upload progress

以下代码将文件上传到服务器显示带有百分比的进度对话框,没有任何问题。

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 代码显示带有百分比的文件上传进度对话框。 我们如何获取用于计算 Apache 代码的进度对话框百分比的 bytesRead 值?

实现相同的任何建议/提示都会有所帮助。

最佳答案

虽然有点棘手,但你可以实现它。我发现这个问题真的很有帮助 .所以请通过这个让我知道

This is the details Discussion and Code

关于android - 使用 Apache API 在 Android 中显示文件上传进度百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9707943/

相关文章:

android - 在不发布应用程序的情况下使用 GCM

java - 在 android : UnsatisfiedLinking Error and Force closing Application 中使用 jni/ndk

xml - ActionScript 3.0 如何使用从 XML 加载的多个文件在 for 循环中创建 ProgressEvent 实例

javascript - 管理多个文件上传的进度条

android - BroadcastReceiver 不接收来自 IntentService 的广播

android - WebView 和软键盘问题

javascript - 有没有办法在 Keystone JS 上上传视频?

c# - 调用 HttpRequest.GetBufferlessInputStream 后不支持此方法

javascript - Adler32 javascript中文件的校验和

Django文件上传进度获取缓存返回无