Upload Imagee to Google Cloud Storage Java

GSP168

Google Cloud Self-Paced Labs

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

  1. 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.

    Open Google Console

  2. 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.

    Sign in

    Tip: Open up the tabs in split windows, side-by-side.

  3. 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).

  4. 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.

Cloud Shell icon

Click Continue.

cloudshell_continue.png

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:

Cloud Shell Terminal

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:

gcloud auth list

(Output)

ACTIVE: * Account: student-01-xxxxxxxxxxxx@qwiklabs.internet To set the active account, run: $ gcloud config set account `ACCOUNT`

You lot can list the projection ID with this command:

gcloud config listing project

(Output)

[cadre] project = <project_ID>

(Example output)

[core] projection = qwiklabs-gcp-44776a13dea667a6

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.

git clone https://github.com/GoogleCloudPlatform/training-data-annotator

Configure and run the Quiz application

  1. Modify the working directory:

    cd ~/preparation-information-analyst/courses/developingapps/java/cloudstorage/first
  2. 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
  3. To run the application, execute the following control:

    mvn spring-boot:run

Review the Quiz awarding

  1. To view the application, click Spider web preview > Preview on port 8080.

    cb2421be3a8c4774.png

  2. 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.

    a0d62fddf38cba78.png

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

  1. From Deject Trounce, click Launch the code editor icon (looks like a pencil) to launch the code editor.

    pencil.png

  2. Navigate to /grooming-data-analyst/courses/developingapps/java/cloudstorage/start folder using the file browser panel on the left side of the editor.

Review the Leap Kicking Spider web application

  1. Select new_question.html file in the .../src/chief/resource/templates folder.

    This file contains the Thyme template for the Create Question form. Find how the form uses multipart/grade-data as the enc-type, and the two grade controls for images and videos:

    • A file upload control called image
    • A subconscious field called imageUrl
  2. Select the .../src/principal/java/com/google/preparation/appdev folder.

    Java file paths are relative to this folder.

  3. Select .../web/QuestionsController.java.

    In this file the Mail handler invokes a method on an image service.

  4. Select the .../services/gcp/cloudstorage/ImageService.coffee file.

    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

  1. Return to Cloud Shell and finish the awarding past pressing Ctrl+C.

  2. 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
  3. 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

  1. In the code editor, motility to the peak of the .../services/gcp/cloudstorage/ImageService.java file.

  2. 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
  3. Construct a Cloud Storage client named storage using the StorageOptions grade.

    // 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
  4. Declare a String named bucketName, and annotate information technology with a Spring value annotation to retrieve the value from a holding named google.storage.bucket.

  5. Declare a constant named bucket to reference the Cloud Storage bucket.

// TODO: Get the name of the Cloud Storage bucket // Apply a Spring @Value annotation to get the value // Get the value using ${google.storage.bucket} // This references the GCLOUD_BUCKET environs variable @Value("${google.storage.bucket}") private Cord bucketName; // END TODO

ImageService.coffee

package com.google.training.appdev.services.gcp.cloudstorage; // TODO: Write a start import for Cloud Storage import com.google.deject.storage.*; // End TODO import org.springframework.beans.manufacturing plant.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.ArrayList; import coffee.util.Arrays; @Service public class ImageService { // TODO: Create the storage client // The StorageOptions class has a getDefaultInstance() // static method. // Use the getService() method to become the storage client individual static Storage storage = StorageOptions .getDefaultInstance() .getService(); // Cease TODO // TODO: Get the name of the Cloud Storage saucepan // Utilize a Jump @Value notation to get the value // Get the value using ${google.storage.bucket} // This references the GCLOUD_BUCKET surroundings variable @Value("${google.storage.bucket}") individual String bucketName; // END TODO

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.

  1. Declare a BlobInfo object and initialize it using the storage client object. Customize the BlobInfo object using its Builder. 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
  2. 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

public Cord saveImage(MultipartFile file) throws IOException { // The existing code in the method creates a unique proper name // based on the file's original proper name. It has a // prefix generated using the electric current engagement and time. // This should ensure that a new file upload won't // overwrite an existing object in the bucket String fileName = System.nanoTime() + file.getOriginalFilename(); // TODO: Create a new Cloud Storage object // Apply the BlobInfo course to represent this object // Use the BlobInfo.Builder to customize the Blob // Gear up 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.Part.READER)))) .build(), file.getInputStream()); // Stop TODO // TODO: Cloud Storage public URLs are in the course: // https://storage.googleapis.com/[BUCKET]/[OBJECT] // Use Cord concatenation to return the URL render "https://storage-download.googleapis.com/" + bucketName + "/" + fileName; // END TODO }

Run the awarding and create a Cloud Storage object

  1. Save .../services/gcp/cloudstorage/ImageService.java and so render to the Cloud Crush.

  2. Start the awarding by typing

    mvn jump-boot:run
  3. Download an image file to your local machine from here.

  4. In Cloud Beat, click Spider web preview > Preview on port 8080 to preview the Quiz awarding.

  5. Click the Create Question link.

  6. 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.png file you lot previously downloaded
    Answer 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
  7. Render to the Cloud Console and navigate to Navigation carte du jour > Storage.

  8. 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

  1. Add /api/quizzes/gcp to 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 imageUrl holding should have a value corresponding to the new object you lot created in Cloud Storage.

  2. Return to the application home page and click the Have Test link.

  3. 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

completion_badge_Application_Development_-_Java-135.png completion_badge_Cloud_Development-135.png

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.

leealthatede50.blogspot.com

Source: https://www.cloudskillsboost.google/focuses/1141?parent=catalog

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel