Upload File to Google Cloud Storage Java

i. Overview

Spring Framework provides a ResourceLoader brainchild to easily read and write files from diverse sources, such as the file arrangement, classpath, or spider web. You merely need to specify the URI to the resource using the well-known protocol prefix. For example, to access a file on the local file organization, you would specify a URI like file:/data/config.yaml.

You'll write a Spring Boot app that will access files stored in Cloud Storage by using the Spring Resource brainchild and the gs: protocol prefix.

You'll do that by using Cloud Beat out and the Cloud SDK gcloud command-line tool.

What you'll larn

  • How to use the Cloud Storage Leap Boot starter
  • How to admission files in Cloud Storage with Spring
  • How to utilise Spring'southward Resource and WritableResource abstractions

What you'll need

  • A Google Deject project
  • A browser, such as Google Chrome
  • Familiarity with standard Linux text editors, such as Vim, Emacs, and GNU Nano

How will you utilize the codelab?

Read only Read and complete the exercises

How would you charge per unit your experience with building HTML and CSS web apps?

Novice Intermediate Expert

How would yous rate your experience with using Google Cloud services?

Novice Intermediate Proficient

ii. Setup and requirements

Self-paced surroundings setup

  1. Sign in to Cloud Console and create a new project or reuse an existing one. (If you don't already have a Gmail or Thousand Suite business relationship, you must create i.)

dMbN6g9RawQj_VXCSYpdYncY-DbaRzr2GbnwoV7jFf1u3avxJtmGPmKpMYgiaMH-qu80a_NJ9p2IIXFppYk8x3wyymZXavjglNLJJhuXieCem56H30hwXtd8PvXGpXJO9gEUDu3cZw

ci9Oe6PgnbNuSYlMyvbXF1JdQyiHoEgnhl4PlV_MFagm2ppzhueRkqX4eLjJllZco_2zCp0V0bpTupUSKji9KkQyWqj11pqit1K1faS1V6aFxLGQdkuzGp4rsQTan7F01iePL5DtqQ

8-tA_Lheyo8SscAVKrGii2coplQp2_D1Iosb2ViABY0UUO1A8cimXUu6Wf1R9zJIRExL5OB2j946aIiFtyKTzxDcNnuznmR45vZ2HMoK3o67jxuoUJCAnqvEX6NgPGFjCVNgASc-lg

Remember the project ID, a unique proper name across all Google Cloud projects (the name above has already been taken and volition not piece of work for y'all, sorry!). It will exist referred to later in this codelab as PROJECT_ID.

  1. Next, you'll need to enable billing in Deject Panel in lodge to employ Google Cloud resources.

Running through this codelab shouldn't cost much, if annihilation at all. Be certain to to follow whatever instructions in the "Cleaning upward" section which advises y'all how to close downwardly resources then y'all don't incur billing beyond this tutorial. New users of Google Deject are eligible for the $300USD Free Trial program.

Cloud Vanquish

You lot'll employ Cloud Shell, a command-line surround running in Google Cloud.

Activate Cloud Shell

  1. From the Cloud Panel, click Activate Cloud Shell H7JlbhKGHITmsxhQIcLwoe5HXZMhDlYue4K-SPszMxUxDjIeWfOHBfxDHYpmLQTzUmQ7Xx8o6OJUlANnQF0iBuUyfp1RzVad_4nCa0Zz5LtwBlUZFXFCWFrmrWZLqg1MkZz2LdgUDQ.

zlNW0HehB_AFW1qZ4AyebSQUdWm95n7TbnOr7UVm3j9dFcg6oWApJRlC0jnU1Mvb-IQp-trP1Px8xKNwt6o3pP6fyih947sEhOFI4IRF0W7WZk6hFqZDUGXQQXrw21GuMm2ecHrbzQ

If you've never started Deject Shell before, you'll exist presented with an intermediate screen (below the fold) describing what it is. If that'southward the case, click Continue (and y'all won't e'er come across it again). Here'south what that 1-time screen looks like:

kEPbNAo_w5C_pi9QvhFwWwky1cX8hr_xEMGWySNIoMCdi-Djx9AQRqWn-__DmEpC7vKgUtl-feTcv-wBxJ8NwzzAp7mY65-fi2LJo4twUoewT1SUjd6Y3h81RG3rKIkqhoVlFR-G7w

It should only accept a few moments to provision and connect to Cloud Shell.

pTv5mEKzWMWp5VBrg2eGcuRPv9dLInPToS-mohlrqDASyYGWnZ_SwE-MzOWHe76ZdCSmw0kgWogSJv27lrQE8pvA5OD6P1I47nz8vrAdK7yR1NseZKJvcxAZrPb8wRxoqyTpD-gbhA

This virtual machine is loaded with all the evolution tools you'll demand. It offers a persistent 5GB abode directory and runs in Google Cloud, greatly enhancing network performance and authentication. Much, if not all, of your work in this codelab tin can be washed with simply a browser or your Chromebook.

One time connected to Deject Crush, you lot should see that you are already authenticated and that the project is already ready to your project ID.

  1. Run the following command in Cloud Shell to confirm that you lot are authenticated:
gcloud auth list          

Command output

            Credentialed Accounts Agile  ACCOUNT *       <my_account>@<my_domain.com>  To set the active account, run:     $ gcloud config set business relationship `ACCOUNT`          
gcloud config list projection          

Command output

[core] projection = <PROJECT_ID>          

If it is not, you can gear up it with this control:

gcloud config set project <PROJECT_ID>          

Command output

Updated property [core/project].          

3. Create a file in Cloud Storage

After Cloud Crush launches, you tin start creating files and transferring them to Cloud Storage.

Create a file named my-file.txt:

$ echo "Hi World from GCS" > my-file.txt          

And so create a new unique bucket in Cloud Storage and transfer the file there using gsutil.

$ Saucepan=spring-bucket-$USER $ gsutil makebucket gs://$BUCKET $ gsutil copy my-file.txt gs://$BUCKET          

Navigate to the storage browser in Cloud Storage, and verify that the bucket and the file are there.

four. Initialize a Spring Kick app

Showtime writing the app by using the command line to generate a new Spring Boot app with Spring Initializr:

$ curl https://start.spring.io/starter.tgz \ -d dependencies=spider web,deject-gcp-storage -d baseDir=spring-gcs | tar -xzvf -          

Note that the Initializr will automatically add the spring-boot-starter-spider web and spring-cloud-gcp-starter-storage to your dependencies in the pom.xml of the template app.

Change to the directory of the template app:

$ cd leap-gcs          

Build and run the app using Maven.

$ ./mvnw bound-kick:run          

The app volition offset listening on port 8080. Open a new Cloud Shell tab and run ringlet to admission the app.

$ ringlet localhost:8080          

You should get a 404 response because the app doesn't do anything useful notwithstanding. Return to the previous Deject Shell tab where the app is running and kill it with Control+C (Command+C on Macintosh).

5. Read the file in Cloud Storage

Modify your Spring Boot app to admission my-file.txt, the file that you previously stored in Deject Storage. Your goal is to simply return the contents of the file via HTTP.

In the post-obit instructions, y'all'll use Vim to edit the files, but you lot can as well apply Emacs, GNU Nano, or the built-in code editor in Cloud Shell:

cae99c53d157378f.png

$ cd ~/spring-gcs          

Add a REST controller GcsController to the app.

$ half-dozen src/principal/java/com/example/demo/GcsController.java          

Paste the following code, and don't forget to set up the resource URI with the bucket that yous created previously. You tin can check the saucepan by running repeat $BUCKET command.

src/master/java/com/instance/demo/GcsController.java

            parcel com.example.demo;  import java.io.IOException; import java.nio.charset.Charset; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.demark.notation.RestController;  @RestController public form GcsController {    @Value("gs://REPLACE_WITH_YOUR_BUCKET/my-file.txt")   private Resource gcsFile;    @GetMapping   public String readGcsFile() throws IOException {     render StreamUtils.copyToString(         gcsFile.getInputStream(),         Charset.defaultCharset());   } }                      

Build and run the app with Maven:

$ ./mvnw spring-kicking:run          

The app starts listening on port 8080. Open a new Cloud Shell tab and run whorl to admission the app.

$ curlicue localhost:8080          

You should now see that the contents of the file returned from the app. Get to the previous Cloud Trounce tab where the app is running and kill it with Command+C (Control+C on Macintosh).

half-dozen. Write to the file in Cloud Storage

You read the contents of the file in Cloud Storage and exposed it through a Bound Remainder controller. Now, change the contents of the file by posting the new file content to the same HTTP endpoint.

You need to add another method to GcsController that will answer to HTTP POST and write the information to your file in Cloud Storage. This fourth dimension, cast the Spring Resource to WritableResource.

Update the GcsController with boosted imports that y'all demand.

src/main/java/com/example/demo/GcsController.java

            import java.io.OutputStream; import org.springframework.core.io.WritableResource; import org.springframework.web.bind.note.RequestBody; import org.springframework.spider web.bind.note.PostMapping;                      

Add the new endpoint method to the controller.

src/main/coffee/com/case/demo/GcsController.java

            @RestController public class GcsController {   @PostMapping   Cord writeGcs(@RequestBody String data) throws IOException {     try (OutputStream os = ((WritableResource) gcsFile).getOutputStream()) {       os.write(information.getBytes());     }     render "file was updated\n";   }   ... }                      

Build and run the app with Maven:

$ ./mvnw spring-boot:run          

The app starts listening on port 8080. Open up upwardly a new Cloud Shell tab and run curl to post a message to the app.

$ roll -d 'new message' -H 'Content-Type: text/plain' localhost:8080          

You should encounter a confirmation that the contents of the file were updated. However, verify that by doing a GET.

$ curl localhost:8080          

You should see the updated contents of the file returned from the app. Return to the previous Cloud Shell tab where the app is running and kill information technology with Control+C (Command+C on Macintosh).

7. Congratulations!

You learned to utilise the Spring Resource abstraction to easily access files in Cloud Storage. You wrote a Leap Kick web app that can read and write to a file in Cloud Storage. You also learned about the Leap Kick starter for Cloud Storage that enables that functionality.

Larn More

  • Deject Storage
  • Spring Deject Google Deject Project
  • Spring on Google Cloud GitHub repository
  • Coffee on Google Cloud

License

This piece of work is licensed nether a Artistic Commons Attribution 2.0 Generic License.

chickbuthationd.blogspot.com

Source: https://codelabs.developers.google.com/codelabs/spring-cloud-gcp-gcs/

0 Response to "Upload File to Google Cloud Storage Java"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel