2

I have a FileOutputStream and am trying to get the contents of this file on a remote server. The server has an API to which I should POST the contents of the file (which is an .xls file). The API requires me to POST the data to its API URL and set the ContentType to that of an .xls file in this case.

The code is something as follows:

try { 
      outputFile = new FileOutputStream("myfile.xls");
} 
catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
}

handle.sendRequest("https://server/API/file/id", "POST", "application/vnd.ms-excel", data);

How can I send the data of the file in the stream to the server?

Aaa
  • 23
  • 3

1 Answers1

0

FileOutputStream is used to write files, and it seems like you need to read file, then you should use FileInputStream. Read file content to byte array Convert InputStream to byte array in Java

try (InputStream is = new FileInputStream("myfile.xls")) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] dataPart = new byte[16384];
    while ((nRead = is.read(dataPart, 0, dataPart.length)) != -1) {
      buffer.write(dataPart, 0, nRead);
    }
    buffer.flush();
    byte[] data = buffer.toByteArray();

    handle.sendRequest("https://server/API/file/id", "POST", "application/vnd.ms-excel", data);
}
Community
  • 1
  • 1
Yurii K
  • 162
  • 1
  • 5
  • 1
    Using [Files.readAllBytes](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllBytes-java.nio.file.Path-) is the preferred way to do this. It's also considerably shorter code. – VGR Jul 19 '15 at 23:46