以下是将文件上传到Google云存储的代码,
public static void uploadFile(String name, String contentType, File file, String bucketName)
throws IOException, GeneralSecurityException {
InputStreamContent contentStream = new InputStreamContent(contentType, new FileInputStream(file));
// Setting the length improves upload performance
contentStream.setLength(file.length());
StorageObject objectMetadata = new StorageObject()
// Set the destination object name
.setName(name)
// Set the access control list to publicly read-only
.setAcl(Arrays.asList(new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
// Do the insert
Storage client = StorageFactory.getService();
Storage.Objects.Insert insertRequest = client.objects().insert(bucketName, objectMetadata, contentStream);
StorageObject response =insertRequest.execute();
System.out.println("Storage insert response: "+response.toPrettyString());
}
如何从响应对象中捕获错误?
答案 0 :(得分:0)
错误在响应对象中不存在。相反,您将看到生成异常。您可以catch (GoogleJsonResponseException e)
并检查GoogleJsonError
中的e.getDetails()
。见an example。可以应用其他异常,包括一些从不产生JSON输出的异常。