4

我正在尝试将一些大文件从 Android 设备上传到 .Net Web 服务。此 Web 服务已设置为接受这些文件作为 POST 参数,并且这些文件必须作为 Base64 编码字符串发送。

我已经能够使用Christian d'Heureuse 的这个库将文件转换为 Base64 字符串,以字节为单位计算字符串的大小并将其发送出去,但是我之前使用的方法涉及将整个文件加载到内存中在处理大文件时导致内存不足错误,这并不意外。

我一直在尝试将文件分块转换为Base64,并在转换时通过连接(使用数据输出流对象)流式传输这些数据,因此不需要一次性将整个文件加载到内存中在转换文件之前,我似乎无法准确计算出请求的 Content-Length 的大小——我通常看起来大约是 10 个字节——令人沮丧的是,它偶尔会起作用!

我还发现,在某些情况下,当这确实有效时,服务器会返回以下错误消息“Base64 字符数组的大小无效”。我认为这是填充字符的问题,但是我看不出我的代码有问题,对此问题的一些建议将不胜感激!

这是生成请求并流式传输数据的代码:

    try
{


    HttpURLConnection connection = null;

    DataOutputStream outputStream = null;

    DataInputStream inputStream = null;

    //This is the path to the file
    String pathToOurFile = Environment
            .getExternalStorageDirectory().getPath()
            + "/path/to/the/file.zip";

    String urlServer = "https://www.someserver.com/somewebservice/";

    int bytesRead, bytesAvailable, bufferSize;

    byte[] buffer;

    int maxBufferSize = 456;


    //The parameters of the POST request - File Data is the file in question as a Base64 String
    String params = "Username=foo&Password=bar&FileData=";

    File sizeCheck = new File(pathToOurFile);

    Integer zipSize = (int) sizeCheck.length();

    Integer paddingRequired = ((zipSize * 8) / 6) % 3;

    Integer base64ZipSize = ((zipSize * 8) / 6)
            + ((zipSize * 8) / 6) % 3;

    Integer paramLength = params.getBytes().length;

    //Code to work out the number of lines required, assuming we create a new
    //line every 76 characters - this is used t work out the number of
    //extra bytes required for new line characters
    Integer numberOfLines = base64ZipSize / 76;

    Log.i(TAG, "numberOfLines: " + numberOfLines);

    Integer newLineLength = System.getProperty("line.separator")
            .getBytes().length;

    //This works out the total length of the Content
    Integer totalLength = paramLength + base64ZipSize
            + (numberOfLines * newLineLength) + paddingRequired;

    Log.i(TAG, "total Length: " + totalLength);

    FileInputStream fileInputStream = new FileInputStream(new File(
            pathToOurFile));

    URL url = new URL(urlServer);

    connection = (HttpURLConnection) url.openConnection();

    connection.setDoInput(true);

    connection.setDoOutput(true);

    connection.setUseCaches(false);

    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");

    connection.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded;");

    connection.setRequestProperty("Content-Length", ""
            + totalLength); // number of bytes

    outputStream = new DataOutputStream(
            connection.getOutputStream());

    //Write out the parameters to the data output stream
    outputStream.writeBytes(params);

    bytesAvailable = fileInputStream.available();

    bufferSize = Math.min(bytesAvailable, maxBufferSize);

    buffer = new byte[bufferSize];

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

    Integer totalSent = paramLength;

    Integer enLen = 0;


    //Convert the file to Base64 and Stream the result to the
    //Data output stream
    while (bytesRead > 0)
    {
        String convetedBase64 = Base64Coder.encodeLines(buffer);
        convetedBase64 = convetedBase64.replace("=", "");

        if (totalSent >= (totalLength - 616))
        {
            Log.i(TAG, "about to send last chunk of data");
            convetedBase64 = convetedBase64.substring(0,
                    convetedBase64.length() - 1);
        }

        Log.i(TAG,
                "next data chunk to send: "
                        + convetedBase64.getBytes().length);
        Log.i(TAG, "'" + convetedBase64 + "'");

        enLen = enLen + convetedBase64.length();
        outputStream.writeBytes(convetedBase64);

        totalSent = totalSent + convetedBase64.getBytes().length;

        Log.i(TAG, "total sent " + totalSent);
        Log.i(TAG, "actual size: " + outputStream.size());

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        bytesRead = fileInputStream.read(buffer, 0, bufferSize); // read
                                                                    // into
                                                                    // the
                                                                    // buffer
    }

    Log.i(TAG, "enLen: " + enLen);
    Log.i(TAG, "paddingRequired: " + paddingRequired);

    for (int x = 0; x < paddingRequired; x++)
    {
        outputStream.writeBytes("=");
    }

    InputStream is2 = connection.getInputStream();
    String output = IOUtils.toString(is2);
    Log.i(TAG, "Got server response: " + output);
    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
}
catch (Exception ex)
{
    Log.e(TAG, "caught an exception:" + ex.getMessage());
}

如果有人能指出我的代码中可能导致这种情况的任何错误,或者提出一种更好的转换和上传文件的方法,我将不胜感激。

4

1 回答 1

1

太好了......我确实设法找到了一些解决这个问题的方法,以防万一有人偶然发现这个问题,我会把它们留在这里:

第一个是将数据写入一个临时文件,这样我就可以在转换后以字节为单位获得大小 - 一开始似乎是个好主意,但效率低下,在发现其他方法后似乎很愚蠢。

另一种方法是不指定内容长度(我不知道你可以这样做!)。不幸的是,Android 仍然试图为上传分配足够的内存,这导致了问题。

如果您指定使用 ChunkedStreamingMode Android 的连接,则播放良好并缓冲上传,节省使用的 ram(除了 2.2 上的一个奇怪错误)。

代码如下:

httppost.setDoInput(true);
httppost.setDoOutput(true);
httppost.setRequestMethod("POST");
httppost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httppost.setChunkedStreamingMode(0); //This specifies the size of the chunks - 0 uses the system default

DataOutputStream dos = new DataOutputStream(httppost.getOutputStream());
dos.writeBytes(content); //This code write out the rest of the post body first, for example username or password

try
{
    BufferedInputStream dis = new BufferedInputStream(new FileInputStream("path/to/some/file"), 2048);

    byte[] in = new byte[512];

    while (dis.read(in)) > 0)
    {
        dos.write(Base64.encode(in, Base64.URL_SAFE)); //This writes out the Base64 data
                                                       //I used the web safe base64 to save URL encoding it again
                                                       //However your server must support this
        dos.write(newLine); //this write out a newline character
    }

dos.flush();
dis.close();
dos.close();

我希望这有帮助!!!

于 2012-11-13T20:21:38.463 回答