[英]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.