我有一个休息端点,它接受一个对象(requestbody)作为输入。我需要读取该对象,将其转换为 csv 并将 csv 上传到谷歌云存储。
我在下面分享我迄今为止所取得的成就:
@GetMapping("/upload")
public void getTranscriptsByDate(@RequestBody SearchRequest searchRequest) throws Exception{
log.info("Search Request {}", searchRequest);
createFileWithSerachCriteria(searchRequest);
uploadFileToGoogleCloudStorage(searchRequest);
}
private void createFileWithSerachCriteria(SearchRequest searchRequest) throws IOException {
String filename = "myFile" + searchRequest.getConversationDate() + ".csv";
String filePath = "C://Users//abc//" + filename;
CSVWriter writer = new CSVWriter(new FileWriter(filePath));
String[] header = { "ID", "NAME" };
writer.writeNext(header);
String[] data = new String[2];
data[0] = searchRequest.getId();
data[1] = searchRequest.getName();
writer.writeNext(data);
writer.close();
}
private void uploadFileToGoogleCloudStorage(SearchRequest searchRequest) throws Exception{
tring filename = "myFile" + searchRequest.getConversationDate() + ".csv";
String filePath = "C://Users//abc//" + filename;
myService.uploadFile(filePath);
}
下面是来自MyService.java的代码
public void uploadFile(String localFilePath) throws Exception{
BlobId blobId = BlobId.of(bucketName, localFilePath);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
storage.createFrom(blobInfo, Paths.get(localFilePath));
}
这段代码运行良好。
我不想在本地写入文件然后读回并上传到云端。我想直接将我的请求对象转换为 csv 并将其上传到云上,而不需要两步(读/写)过程。在官方GCP文档上,我找到了一个流式传输的小示例,但我无法理解它。
是否有可能实现我想要做的事情,即避免读/写并一次性完成。请帮忙。
您可以使用字节流在内存中而不是文件系统中读取和写入文件数据:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
OutputStreamWriter streamWriter = new OutputStreamWriter(stream);
CSVWriter writer = new CSVWriter(streamWriter);
// add data to writer and close
BlobId blobId = BlobId.of(bucketName, someDerivedFilePath);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
storage.createFrom(blobInfo, new ByteArrayInputStream(stream.toByteArray()));
仅供参考,我还没有测试过这个,但看起来应该可行。