Spring Mongo(一)文件下载

系列 - Spring Mongo基本用法

Java

@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();
    }
}

Java

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

相关内容