java - 使用 Springboot 将文件上传到 Google Storage
问题描述
我是 Springboot 的新手。我有以下代码是上传文件。但是,我想使用 Google Cloud。我不确定如何配置 Springboot 以上传到 Google Cloud Buckets。我有带有密钥的 json 文件,但我不确定它应该放在哪里。
这是由控制器设置的。
有没有办法设置上传配置application.properties
?
@Controller
public class UserController {
@Autowired
private UserRepository repo;
@PostMapping("/users/save")
public RedirectView saveUser(User user,
@RequestParam("image") MultipartFile multipartFile) throws IOException {
String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
user.setPhotos(fileName);
User savedUser = repo.save(user);
String uploadDir = "user-photos/" + savedUser.getId();
FileUploadUtil.saveFile(uploadDir, fileName, multipartFile);
return new RedirectView("/users", true);
}
}
谷歌将此作为代码示例发布。
public class UploadObject {
public static void uploadObject(
String projectId, String bucketName, String objectName, String filePath) throws IOException {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
// The ID of your GCS object
// String objectName = "your-object-name";
// The path to your file to upload
// String filePath = "path/to/your/file"
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
BlobId blobId = BlobId.of(bucketName, objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath)));
System.out.println(
"File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
}
}
我implementation ("com.google.cloud:spring-cloud-gcp-starter-storage")
在我的build.gradle.kts
解决方案
推荐阅读
- laravel - 如何更改网站的基本 URL - Laravel 5.4
- python - 根据另一个 DataFrame 选择一个 DataFrame 的列
- java - Hibernate 合并在更新前执行 11000 次选择
- javascript - 电子邮件通知:TypeError:在对象 1 中找不到函数 getColumn
- android - Android,有没有办法在应用程序内更新 Fabric Beta 分布式应用程序?
- powershell - 使用 foreach 循环重命名文件夹匹配模式
- apache-spark - 为什么 _spark_metadata 的所有 parquet 分区文件都在 0 内,但集群有 2 个工作人员?
- tfs - TFS 工作项自定义:开始日期可以在迭代日期之间
- sql - SQL - 两个不同实体之间的 ACID 关系
- javascript - 如何通过 HTML 按钮运行 Python 脚本?