簡體   English   中英

使用和應用程序將帶有signUrl的文件上傳到Google雲存儲

[英]Upload file with signUrl to google cloud storage using and application

我創建了一個Scala應用程序,作為其功能的一部分,它可以將任何類型的文件(BZ2,csv,txt等)上傳到Google雲存儲。

如果我使用直接上傳,則對小文件來說效果很好,但要上傳大文件,谷歌建議使用“ signUrl”,這不是創建文件,也不是更新文件(如果我之前創建過文件),或者拋出任何錯誤異常。

適用於小文件:

val storage: Storage = StorageOptions.getDefaultInstance.getService
val fileContent = Files.readAllBytes(file.toPath)
val fileId: BlobId = BlobId.of(bucketName, s"$folderName/$fileName")
val fileInfo: BlobInfo = BlobInfo.newBuilder(fileId).build()
storage.create(fileInfo, fileContent)

不工作:

val storage: Storage = StorageOptions.getDefaultInstance.getService
val outputPath = s"$folderName/$fileName"
val fileInfo: BlobInfo = BlobInfo.newBuilder(bucketName, outputPath).build()
val optionWrite: SignUrlOption = Storage.SignUrlOption.httpMethod(HttpMethod.PUT)
val signedUrl: URL = storage.signUrl(fileInfo, 30, TimeUnit.MINUTES, optionWrite)
val connection = signedUrl.openConnection
connection.setDoOutput(true)
val out = connection.getOutputStream

val inputStream = Files.newInputStream(file.toPath)
var nextByte = inputStream.read()
while (nextByte != -1) {
 out.write(nextByte)
 nextByte = inputStream.read()
}
out.flush()
inputStream.close()
out.close()

我嘗試逐字節讀取,寫入,使用和字節數組以及使用OutputStreamWriter,但均無效。

我正在使用的庫是:

"com.google.cloud" % "google-cloud-storage" % "1.12.0"

有人知道為什么這行不通嗎? 謝謝

我發現了一種無需使用signURL即可在Google存儲設備中寫入大文件的簡便方法。

我將添加代碼,以防萬一有人發現它有用。

storage.create(fileInfo)
var writer:WriteChannel = storage.get(fileInfo.getBlobId).writer()
var inputStream: InputStream = Files.newInputStream(file.toPath)
val packetToRead: Array[Byte] = new Array[Byte](sizeBlockDefault toInt)
while (inputStream.available() > 0){
  val numBytesReaded = inputStream.read(packetToRead,0,sizeBlockDefault toInt)
  writer.write(ByteBuffer.wrap(packetToRead, 0, numBytesReaded))
}
inputStream.close()
writer.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM