0

I have to send a picture file (can be a video btw), picked or taken on the phone. The issues are the following: - Android version can be pre kitkat - Retrofit accepts a RequestBody which is build with a File or a byte array when I might only have a FileDescriptor

Seeing the other posts, it looks like retrieving an asset from the phone is a real p*** in the *** I understand the question is wide! ....and that is the problem

gropapa
  • 577
  • 6
  • 10

1 Answers1

0

What I came with is the following: - for the picture fis is an inputStream based on the FileDescriptor like

FileInputStream fileInputStream = new FileInputStream(fileDescriptor);

then i read the inputStream in order to get a byteArray

ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] result = null;
    try {
        byte[] input = new byte[fis.available()];
        int read;
        while ((read = fis.read(input)) != -1) {
            out.write(input, 0, read);
        }
        result = out.toByteArray();
        fis.close();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;

after i create a Requestbody as usual, I pass it to retrofit with a special a post multipart method using a special part value as

... , @Nullable @Part("picture\"; filename=\"picture\" ") RequestBody picture ...

That was really hard to find but since retrofit is still in beta it changes a lot and lacks documentation, hope this helps

gropapa
  • 577
  • 6
  • 10
  • 2
    What if file is large? This method loads everything into memory (RAM), so it will throw `OutOfMemoryException` once file exceeds memory limitations ~100mb – Ioane Sharvadze Sep 19 '18 at 10:39
  • Hi and sorry for my very (very) late response, I believe the only answer to this is to implement a multipart upload, doing the same but in multiple steps. – gropapa Jan 13 '19 at 21:36