我正在尝试用 Java 发布一个 API,以从 Azure blob 下载文件(如果存在),但在 openQueryInputStream 处出现异常。
BlobClient blobClient = blobContainerClient.getBlobClient(fileQueuePath + "/" + fileName);
boolean blobExists = blobClient.exists();
if (!blobExists) {
return Response.status(Response.Status.NOT_FOUND)
.entity("File not available in the specified path.")
.build();
}
InputStream is = blobClient.openQueryInputStream();
return Response.ok(is)
.header("content-disposition", "attachment; filename=\"" + fileName + "\"")
.build();
}
我相信您实际上没有正确创建下载流。
您可能想尝试以下更改:
if (!blobExists) {
return Response.status(Response.Status.NOT_FOUND)
.entity("File not available in the specified path.")
.build();
}
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
blobClient.downloadStream(outputStream);
final byte[] = outputStream.toByteArray();
ByteArrayInputStream inputStream = new
ByteArrayInputStream(bytes);
ByteArrayResource resource = new ByteArrayResource(bytes);
return Response.ok(outputStream)
.header("content-disposition", "attachment; filename=\"" + fileName + "\"")
.build();
} catch(IOException e) {
// Do something with the exception?
}
如果您愿意,您可以使用
BlobInputStream
来执行相同操作:
try (BlobInputStream blobStream = blobClient.openInputStream()) {
blobStream.read();
// Now return this stream.
} catch (IOException e) {
// DO something?
}