输入哈希值后如何在Corda中下载jar文件?

时间:2018-07-02 09:47:22

标签: corda

我试图上传一个zip文件并获得了哈希值。现在,我已经调用了一个api。在这种情况下,我给出了散列来下载文件。但是我无法下载该文件。

@PUT
@Path("download_file")
fun createIOU(
        @QueryParam("sechash") sechash: String
): Response {

    val SecuHash = SecureHash.parse(sechash)
    return try {
        val attachmentJr = downloadAttachment(rpcOps, SecuHash)
        println("jar      :"+attachmentJr)
        Response.status(CREATED).entity("Transaction id ${attachmentJr} committed to ledger.\n").build()
    } catch (ex: Throwable) {
        logger.error(ex.message, ex)
        Response.status(BAD_REQUEST).entity(ex.message!!).build()
    }
}

private fun downloadAttachment(proxy: CordaRPCOps, attachmentHash: SecureHash) {
    //Get the attachmentJar from node for attachmentHash.
    val attachmentJar = proxy.openAttachment(attachmentHash)
    //Read the content of Jar to get file name and data.
    var file_name_data: Pair<String, ByteArray>? = null
    JarInputStream(attachmentJar).use { jar ->
        while (true) {
            val nje = jar.nextEntry ?: break
            if (nje.isDirectory) {
                continue
            }
            file_name_data = Pair(nje.name, jar.readBytes())

        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可能想看看这个博客。它详细说明了如何在Corda中实现附件的上传和下载。

它演示了使用两种不同方法下载附件的方法:

使用附件ID /哈希

@GetMapping("/{hash}")
fun downloadByHash(@PathVariable hash: String): ResponseEntity<Resource> {
    val inputStream = InputStreamResource(proxy.openAttachment(SecureHash.parse(hash)))
    return ResponseEntity.ok().header(
        HttpHeaders.CONTENT_DISPOSITION,
        "attachment; filename=\"$hash.zip\""
    ).body(inputStream)
}

使用附件名称

@GetMapping
fun downloadByName(@RequestParam name: String): ResponseEntity<Resource> {
  val attachmentIds: List<AttachmentId> = proxy.queryAttachments(
    AttachmentQueryCriteria.AttachmentsQueryCriteria(filenameCondition = Builder.equal(name)),
    null
  )
  val inputStreams = attachmentIds.map { proxy.openAttachment(it) }
  val zipToReturn = if (inputStreams.size == 1) {
    inputStreams.single()
  } else {
    combineZips(inputStreams, name)
  }
  return ResponseEntity.ok().header(
    HttpHeaders.CONTENT_DISPOSITION,
    "attachment; filename=\"$name.zip\""
  ).body(InputStreamResource(zipToReturn))
}

private fun combineZips(inputStreams: List<InputStream>, filename: String): InputStream {
  val zipName = "$filename-${UUID.randomUUID()}.zip"
  FileOutputStream(zipName).use { fileOutputStream ->
    ZipOutputStream(fileOutputStream).use { zipOutputStream ->
      inputStreams.forEachIndexed { index, inputStream ->
        val zipEntry = ZipEntry("$filename-$index.zip")
        zipOutputStream.putNextEntry(zipEntry)
        inputStream.copyTo(zipOutputStream, 1024)
      }
    }
  }
  return try {
    FileInputStream(zipName)
  } finally {
    Files.deleteIfExists(Paths.get(zipName))
  }
}

https://lankydan.dev/uploading-and-downloading-attachments-in-corda