【问题标题】:Java: Transfer local file to output stream of serverJava:将本地文件传输到服务器的输出流
【发布时间】:2023-03-17 11:15:02
【问题描述】:

我有一个 FileOutputStream 并试图在远程服务器上获取此文件的内容。服务器有一个 API,我应该向其发布文件的内容(这是一个 .xls 文件)。在这种情况下,API 要求我将数据发布到其 API URL 并将 ContentType 设置为 .xls 文件。

代码如下:

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);

如何将流中文件的数据发送到服务器?

【问题讨论】:

    标签: java file api stream server


    【解决方案1】:

    FileOutputStream 是用来写文件的,看来你需要读文件,那么你应该使用 FileInputStream。 将文件内容读入字节数组 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);
    }
    

    【讨论】:

    • 使用Files.readAllBytes 是执行此操作的首选方式。它的代码也相当短。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2020-09-26
    • 1970-01-01
    • 2015-11-21
    • 2017-02-16
    • 2014-07-17
    相关资源
    最近更新 更多