5

I want to get from an Android Uri (of the kind returned by onActivityResult) to a simple byte array, in order to upload a file as part of a multipart message. Can anyone provide an example of how to get from a Uri to a byte[] array?

Edit: I mean the android.net.Uri Uri

Manoj Kumar
  • 1,510
  • 3
  • 20
  • 40

1 Answers1

14

After putting together some SO examples and google group codes, i'm able to acheive it by this code:

Uri data = result.getData();   
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
FileInputStream fis;  
try {  
    fis = new FileInputStream(new File(data.getPath()));  
    byte[] buf = new byte[1024];  
    int n;  
    while (-1 != (n = fis.read(buf)))  
        baos.write(buf, 0, n);  
} catch (Exception e) {  
    e.printStackTrace();  
}  
byte[] bbytes = baos.toByteArray();
Yusril Maulidan Raji
  • 1,682
  • 1
  • 21
  • 46
Manoj Kumar
  • 1,510
  • 3
  • 20
  • 40
  • 2
    I get this error: java.io.FileNotFoundException: /document/primary:Simon/Sample file/Financial Sample.xlsx: open failed: ENOENT (No such file or directory). Any idea? – Yusril Maulidan Raji Sep 16 '19 at 09:39