Upload Imagee to Google Cloud Storage Java
GSP168
Overview
Cloud Storage allows world-broad storage and retrieval of any corporeality of data at any time. Yous can utilise Deject Storage for a range of scenarios including serving website content, storing data for archival and disaster recovery, or distributing big data objects to users via direct download.
In this lab yous'll configure an awarding to utilize Cloud Storage to store and retrieve application data. The awarding is an online Quiz, the data is the form data, including an image you upload from your local auto.
Objectives
In this lab, y'all learn how to perform the post-obit tasks:
-
Gear up Cloud Crush as your evolution environment
-
Update the application code to integrate Deject Datastore
-
Use the Quiz application to upload an image file into Cloud Storage and view the image in the Quiz
Setup and requirements
Before you click the Start Lab button
Read these instructions. Labs are timed and you lot cannot suspension them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources volition be made bachelor to you.
This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. Information technology does and so by giving you lot new, temporary credentials that yous utilize to sign in and access Google Cloud for the elapsing of the lab.
What you need
To complete this lab, you lot demand:
- Access to a standard internet browser (Chrome browser recommended).
- Fourth dimension to complete the lab.
Notation: If you already have your own personal Google Cloud business relationship or project, practice non utilise it for this lab.
Notation: If you are using a Chrome OS device, open up an Incognito window to run this lab.
How to start your lab and sign in to the Google Deject Console
-
Click the Start Lab button. If you lot need to pay for the lab, a pop-up opens for yous to select your payment method. On the left is a panel populated with the temporary credentials that you must use for this lab.
-
Copy the username, and and so click Open Google Console. The lab spins upwardly resource, and then opens some other tab that shows the Sign in folio.
Tip: Open up the tabs in split windows, side-by-side.
-
In the Sign in page, paste the username that you copied from the left console. And then copy and paste the password.
Of import: You must use the credentials from the left panel. Do non utilize your Google Cloud Grooming credentials. If you have your own Google Cloud account, exercise non employ it for this lab (avoids incurring charges).
-
Click through the subsequent pages:
- Accept the terms and conditions.
- Do not add recovery options or two-factor authentication (considering this is a temporary account).
- Exercise not sign upward for gratis trials.
Subsequently a few moments, the Cloud Panel opens in this tab.
Activate Cloud Beat out
Cloud Shell is a virtual machine that is loaded with development tools. Information technology offers a persistent 5GB abode directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resource.
In the Cloud Panel, in the top correct toolbar, click the Activate Cloud Shell button.
Click Continue.
It takes a few moments to provision and connect to the environment. When you are continued, you are already authenticated, and the project is set to your PROJECT_ID. For instance:
gcloud is the control-line tool for Google Cloud. It comes pre-installed on Deject Shell and supports tab-completion.
Yous can listing the active account name with this command:
(Output)
You lot can list the projection ID with this command:
(Output)
(Example output)
Review the Quiz application
In this section, you access Cloud Shell, clone the git repository containing the Quiz awarding, and run the application.
Clone source lawmaking in Cloud Trounce
Clone the repository for the form.
Configure and run the Quiz application
-
Modify the working directory:
cd ~/preparation-information-analyst/courses/developingapps/java/cloudstorage/first -
Configure the awarding:
. prepare_environment.sh This script file:
- Creates an App Engine awarding
- Exports an environs variable
GCLOUD_PROJECT - Runs
mvn clean install - Prints out the Project ID.
When the application has been configured, y'all'll see output similar to the post-obit:
[INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 35.702 s [INFO] Finished at: 2018-05-20T21:22:33-04:00 [INFO] Final Memory: 35M/86M [INFO] ------------------------------------------------------------------------ Project ID: qwiklabs-gcp-a3b32951ac6cfb59 -
To run the application, execute the following control:
mvn spring-boot:run
Review the Quiz awarding
-
To view the application, click Spider web preview > Preview on port 8080.
-
Click Create Question in the toolbar.
You should see a simple course that contains textboxes for the question and answers and radio buttons to select the correct reply.
The form has a new file upload field that is used to upload an image or video file. In this lab you upload an image file; you would use the aforementioned process to upload a video file.
Examining the Quiz application code
In this section, you lot use the Cloud Shell text editor to review the Quiz application code.
Launch the Cloud Beat out text editor
-
From Deject Trounce, click Launch the code editor icon (looks like a pencil) to launch the code editor.
-
Navigate to
/grooming-data-analyst/courses/developingapps/java/cloudstorage/startfolder using the file browser panel on the left side of the editor.
Review the Leap Kicking Spider web application
-
Select
new_question.htmlfile in the.../src/chief/resource/templatesfolder.This file contains the Thyme template for the Create Question form. Find how the form uses
multipart/grade-dataas theenc-type, and the two grade controls for images and videos:- A file upload control called
image - A subconscious field called
imageUrl
- A file upload control called
-
Select the
.../src/principal/java/com/google/preparation/appdevfolder.Java file paths are relative to this folder.
-
Select
.../web/QuestionsController.java.In this file the Mail handler invokes a method on an image service.
-
Select the
.../services/gcp/cloudstorage/ImageService.coffeefile.This is the file where you lot write lawmaking to salve epitome file data into Deject Storage.
Creating a Deject Storage Bucket
In this section, you create a Cloud Storage saucepan and export an surroundings variable that references it.
Create a Cloud Storage saucepan
-
Return to Cloud Shell and finish the awarding past pressing Ctrl+C.
-
To create a Cloud Storage bucket named
<Projection ID>-media, execute the following command:gsutil mb gs://$DEVSHELL_PROJECT_ID-media Click Check my progress to verify the objective.
Create a storage bucket -
To consign the Cloud Storage bucket name every bit an surroundings variable named
GCLOUD_BUCKET, execute the following command:export GCLOUD_BUCKET=$DEVSHELL_PROJECT_ID-media
Recall that the awarding makes use of environment variables for configuration. This allows the development squad to deploy the application into evolution, test, staging, and production just by changing these variables.
Adding Objects to Cloud Storage
In this department, you write code to save uploaded files into Cloud Storage.
Import and employ the Coffee Cloud Storage Package
-
In the code editor, motility to the peak of the
.../services/gcp/cloudstorage/ImageService.javafile. -
Write a star import for the
com.google.cloud.storage.*package.// TODO: Write a start import for Deject Storage import com.google.cloud.storage.*; // End TODO -
Construct a Cloud Storage client named
storageusing theStorageOptionsgrade.// TODO: Create the storage client // The StorageOptions course has a getDefaultInstance() // static method. // Utilize the getService() method to get the storage client individual static Storage storage = StorageOptions .getDefaultInstance() .getService(); // END TODO -
Declare a String named
bucketName,and annotate information technology with a Spring value annotation to retrieve the value from a holding namedgoogle.storage.bucket. -
Declare a constant named
bucketto reference the Cloud Storage bucket.
ImageService.coffee
Write code to send a file to Cloud Storage
Still updating ImageService.java, motion to the saveImage(MultipartFile file) handler so use the Deject Storage client to upload a file to your Cloud Storage bucket and brand information technology publicly available.
-
Declare a
BlobInfoobject and initialize it using the storage client object. Customize theBlobInfoobject using itsBuilder. Use the option to gear up the Content Type and to set the ACL to allow unauthenticated Read access.// TODO: Create a new Cloud Storage object // Utilise the BlobInfo grade to represent this object // Use the BlobInfo.Builder to customize the Hulk // Set the content blazon from the file // Set the object ACL to Public Read BlobInfo blobInfo = storage.create( BlobInfo.newBuilder(bucketName, fileName) .setContentType(file.getContentType()) .setAcl(new ArrayList<>( Arrays.asList(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER)))) .build(), file.getInputStream()); // Finish TODO -
Return the public URL for the new Deject Storage object as a string.
// TODO: Cloud Storage public URLs are in the course: // https://storage.googleapis.com/[BUCKET]/[OBJECT] // Use Cord concatentation to create render the URL return "https://storage-download.googleapis.com/" + bucketName+ "/" +fileName; // Finish TODO
ImageService.java
Run the awarding and create a Cloud Storage object
-
Save
.../services/gcp/cloudstorage/ImageService.javaand so render to the Cloud Crush. -
Start the awarding by typing
mvn jump-boot:run -
Download an image file to your local machine from here.
-
In Cloud Beat, click Spider web preview > Preview on port 8080 to preview the Quiz awarding.
-
Click the Create Question link.
-
Complete the form with the following values, and then click Save.
Field Value Author Your name Quiz Google Deject Title Which product does this logo relate to? Prototype Upload the Google_Cloud_Storage_logo.pngfile you lot previously downloadedAnswer i App Engine Respond 2 Cloud Storage (and select the Reply 2 radio button to indicate this equally the right answer) Respond 3 Compute Engine Answer 4 Container Engine Click Bank check my progress to verify the objective.
Add Objects to Cloud Storage -
Render to the Cloud Console and navigate to Navigation carte du jour > Storage.
-
On the Storage > Browser page, click the correct bucket (named
<Project ID>-media).Y'all should see your new object named
#UniqueNumber#Google_Cloud_Storage_logo.png.Click Check my progress to verify the objective.
Create a Datastore entity
Run the client application and exam the Cloud Storage public URL
-
Add
/api/quizzes/gcpto the end of the Quiz awarding's URL.You should encounter that the awarding returns JSON data to the client corresponding to the Question you lot added in the spider web application.
{"questions":[{"quiz":"gcp","author":"Mary Smith","title":"Which product does this logo chronicle to?","correctAnswer":2,"imageUrl":"https://storage-download.googleapis.com/qwiklabs-gcp-33f2cf3e36ee1794-media/2293278773582Websites_and_Web_Apps_GCP.png","image":zippo,"id":5629499534213120,"answer1":"App Engine","answer2":"Cloud Storage","answer3":"Compute Engine","answer4":"Container Engine"}]} The
imageUrlholding should have a value corresponding to the new object you lot created in Cloud Storage. -
Return to the application home page and click the Have Test link.
-
Click GCP, and reply each question.
When you get to the question you but added, yous should see the prototype has been formatted inside the client-side web application!
Congratulations!
This concludes the self-paced lab, App Dev: Storing Epitome and Video Files in Cloud Storage - Coffee. Y'all configured a quiz application to utilize Deject Storage to store and recall application data.
Finish your Quest
This lab is part of the Application Development - Java and Cloud Development Quests. A Quest is a serial of related labs that form a learning path. Completing this Quest earns you the badge in a higher place, to recognize your achievement. You lot can make your badge (or badges) public and link to them in your online resume or social media business relationship. Enroll in this Quest and get immediate completion credit if y'all've taken this lab. See other available Quests.
Next steps / larn more
- For more information about application servers, run across Using the Local Development Server.
- Check out Building Scalable and Resilient Web Applications on Google Cloud.
Google Cloud Training & Certification
...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help y'all get up to speed quickly and go along your learning journey. We offer fundamental to avant-garde level grooming, with on-demand, live, and virtual options to suit your decorated schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.
Manual last updated October 18,2021
Lab terminal tested April 30, 2020
Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may exist trademarks of the respective companies with which they are associated.
Source: https://www.cloudskillsboost.google/focuses/1141?parent=catalog
0 Response to "Upload Imagee to Google Cloud Storage Java"
Post a Comment