首页 > 解决方案 > 使用 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

标签: java

解决方案


推荐阅读