T.Vert
T.Vert

Reputation: 279

Get length of data from inputstream opened by content-resolver

I am doing video (and also photo) uploading to the server by using HttpURLConnection.

I have an Uri of a video. I open an InputStream this way:

    InputStream inputStream = context.getContentResolver().openInputStream(uri);

As video file is pretty big, I can't buffer data while writing it into the outputStream. So I need to use setFixedLengthStreamingMode(contentLength) method of HttpURLConnection. But it requires "contentLength". The question is, how to get the length of the video?

Please don't suggest getting filepath. On some devices it works, but it often fails (especially on Android 6). They say Uri doesn't necessarily represent a file.

I also stumbled onto situations when after opening device gallery (with Intent) I receive an Uri of a picture, but I fail trying to get filepath from it. So I believe it's not a good way to get filepath from Uri?

Upvotes: 2

Views: 332

Answers (1)

nandsito
nandsito

Reputation: 3852

Try something like this:

void uploadVideo() {

    InputStream inputStream = context.getContentResolver().openInputStream(uri);

    // Your connection.
    HttpURLConnection connection;

    // Do connection setup, setDoOutput etc.

    // Be sure that the server is able to handle
    // chunked transfer encoding.
    connection.setChunkedStreamingMode(0);

    OutputStream connectionOs = connection.getOutputStream();

    // Read and write a 4 KiB chunk a time.
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        connectionOs.write(buffer, 0, bytesRead);
    }

    // Close streams, do connection etc.
}

UPDATE: added setChunkedStreamingMode

Upvotes: 1

Related Questions