使用sttp将响应另存为scala中的文件

n3schb8v  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(189)

我已经设置了一个api,它按照给定的路径发送文件的数据。我正在尝试从api获取.xlsx文件并将其传递给 XSSFWorkbook 以便进一步处理。为此,我尝试了两种方法:
将内容传递到inputstream,然后将其传递到xssfworkbook。这是一个错误 invalid code lengths set ```
val excelData = getFileContent(remoteFsUrl, filePath, apiKey).right.get
val excelFile = IOUtils.toInputStream(excelData, "UTF-8")
val reader = new XSSFWorkbook(OPCPackage.open(excelFile)) <-- error here
reader.getSheetAt(0)

将文件保存在某个本地路径中并读取它。但它破坏了xlsx文件,就好像我试图将响应保存为postman中的文件一样。

val excelData = getFileContent(remoteFsUrl, filePath, apiKey).right.get
new PrintWriter("filename") { write(excelData); close }
val excelFile = new FileInputStream(new File(filePath))
val reader = new XSSFWorkbook(excelFile)
reader.getSheetAt(0)

我能知道在上述方法中是否有什么错误,或者有什么更好的方法吗?
p、 s:我提到的api是基于fastapi构建的。
编辑:执行 `getFileContent` ```
def getFileContent(url: String, path: String, apiKey: String, timeOut: Int = 300) = {
        val request = basicRequest
            .get(uri"$url/fetchfile?file_path=$path&access_token=$apiKey")
        implicit val backend: SttpBackend[Identity, Nothing, NothingT]
        = HttpURLConnectionBackend(options = SttpBackendOptions.connectionTimeout(timeOut.seconds))
        val response = request.readTimeout(timeOut.seconds).send()
        val someFile = new File("path/t.xlsx")
        val data = response.body.right.get.getBytes
        val bos = new BufferedOutputStream(new FileOutputStream(someFile))
        bos.write(data)
        bos.close()
        println(response)
        response.body
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题