Java 使用Springboot将文件上载到Google存储
我对Springboot不熟悉。我有下面的代码,这是上传一个文件。然而,我想使用谷歌云。 我不知道如何配置Springboot以上传到Google云存储桶。 我有带密钥的json文件,但我不确定它应该放在哪里 这是由控制器设置的 是否有方法从Java 使用Springboot将文件上载到Google存储,java,Java,我对Springboot不熟悉。我有下面的代码,这是上传一个文件。然而,我想使用谷歌云。 我不知道如何配置Springboot以上传到Google云存储桶。 我有带密钥的json文件,但我不确定它应该放在哪里 这是由控制器设置的 是否有方法从应用程序.properties设置上载配置 @Controller public class UserController { @Autowired private UserRepository repo; @Post
应用程序.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);
}
}
在我的build.gradle.kts
中有实现(“com.google.cloud:spring-cloud-gcp-starter-storage”)
,我想可能会对您有所帮助。