Search code examples
javaspring-bootgoogle-cloud-platformspring-cloudspring-cloud-gcp

How to upload new file into GCP bucket?


I've found excellent example how to read/update existing file in GCP bucket:

@RestController
public class WebController {

    @Value("gs://${gcs-resource-test-bucket}/my-file.txt")
    private Resource gcsFile;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String readGcsFile() throws IOException {
        return StreamUtils.copyToString(
                this.gcsFile.getInputStream(),
                Charset.defaultCharset()) + "\n";
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    String writeGcs(@RequestBody String data) throws IOException {
        try (OutputStream os = ((WritableResource) this.gcsFile).getOutputStream()) {
            os.write(data.getBytes());
        }
        return "file was updated\n";
    }
}

But I can't find the way how to upload new file into GCP bucket using spring gloud GCP.

How can I achieve it ?


Solution

  • @Autowired
    private Storage gcs;
    
    public void upload(String report) {
    
        gcs.create(BlobInfo
                        .newBuilder("bucket_name", "fileName.json")
                        .build(),
                report.getBytes());
    
    }