首页 > 解决方案 > 使用带有多部分的HttpUrlConnection上传文件的进度在android中非常快

问题描述

我正在尝试使用带有 HttpUrlConnection POST 方法的多部分上传文件。文件正在正确上传,我收到了回复。但是当我跟踪进度时,即使文件大于 100 MB,它也只会在 1 秒内给出所有进度。似乎进度是将文件写入缓冲区而不是网络输出流。在写入每个数据块后在流上调用 flush() 并没有帮助。似乎刷新只是将流清除到网络并且在写入下一个块之前不等待响应。

这是我上传文件的代码:

//Initialised in Constructor
 boundary = twoHyphens + System.currentTimeMillis() + twoHyphens;

    URL url = new URL(requestURL);
    private HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestMethod("POST");
    httpConn.setRequestProperty("Connection", "Keep-Alive");
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);

   //This method is called to upload a file
   public String uploadFile(String fieldName, File uploadFile) throws IOException, InterruptedException {
    String fileName = uploadFile.getName();
    FileInputStream fileInputStream = new FileInputStream(uploadFile);
    DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(httpConn.getOutputStream()));

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

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    //returns no. of bytes present in fileInputStream
    bytesAvailable = fileInputStream.available();

    bufferSize = 4096;
    buffer = new byte[4096];
    long size = uploadFile.length();

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

     while (bytesRead > 0) {
        int percentage = (int) ((bytesRead / (float) size) * 100);
        dataOutputStream.write(buffer, 0, bufferSize);
        dataOutputStream.flush(); //doesn't help
        bytesAvailable = fileInputStream.available();
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }//This finishes in 1 second

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

    int status = httpConn.getResponseCode();
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = null;

    try {
        if (status == HttpURLConnection.HTTP_OK) {
            reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } else {
            throw new IOException("Server exception with status code: " + status);
        }
    } catch (Exception e) {

    } finally {
        if (reader != null) {
            reader.close();
            httpConn.disconnect();
        }
    }
    return sb.toString();
}

对此的任何帮助或解释都非常感谢。

标签: javaandroidfile-upload

解决方案


写入输出流实际上不会触发网络连接。getResponseCode()正如我在其他答案中详述的那样,您致电时已将数据上传到服务器

仅当您有某种方式要求getResponseCode()报告进度时,否则您无法监控进度。


推荐阅读