Spring Mongo(一)文件下载
系列 - Spring Mongo基本用法
目录
文件保存到Mongo
@Service
public class TaskResultService {
@Autowired
private MongoTemplate mongoTemplate;
private final GridFSBucket gridFSBucket;
public TaskResultService(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
this.gridFSBucket = GridFSBuckets.create(mongoTemplate.getDb(),DEFAULT_RESULT_BUCKET);
}
public String addResult(String csvData,String taskId,String taskUuid) {
if (StringUtils.isEmpty(csvData)) {
csvData=";";
}
InputStream inputStream = new ByteArrayInputStream(csvData.getBytes());
GridFSUploadOptions options = new GridFSUploadOptions()
.metadata(new Document("type", "csv")
.append("aa", xx));
ObjectId fileId = gridFSBucket.uploadFromStream(UUID.randomUUID() + ".csv", inputStream, options);
return fileId.toHexString();
}
}
Mongo读取文件
public String downloadFileAsString(String fileId) {
ObjectId objectId = new ObjectId(fileId);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
gridFSBucket.downloadToStream(objectId, outputStream);
return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
}