Upload File to Vultr From Google Drive

Introduction

Object storage is a popular and scalable method of storing and serving static assets such every bit audio, images, text, PDFs, and other types of unstructured information. Cloud providers offer object storage in add-on to traditional local or block storage, which is used to store dynamic awarding files and databases. Read Object Storage vs. Block Storage to learn about the use cases and differences between the two.

Spaces is a simple object storage service offered by DigitalOcean. In add-on to beingness able to login and upload, manage, and delete stored files through a control console, you tin can as well access your DigitalOcean Space through the command line and the Spaces API.

In this tutorial, we will create a Node.js application that allows a user to upload a file to their DigitalOcean Space by submitting a form on the front-end of a website.

Prerequisites

To follow forth with this tutorial, you will need:

  • A DigitalOcean Space, along with an admission key and undercover access key to your account. Read How To Create a DigitalOcean Space and API Cardinal to go up and running with a DigitalOcean account, create a Space, and gear up an API primal and secret.
  • Node.js and npm installed on your computer. You tin can visit the Node.js Downloads to install the correct version for your operating organization.

You lot should now take a DigitalOcean account, a Space with access key, and Node.js and npm installed on your computer.

Add together Admission Keys to Credentials File

DigitalOcean Spaces is compatible with the Amazon Elementary Storage Service (S3) API, and we will be using the AWS SDK for JavaScript in Node.js to connect to the Space we created.

The first step is to create a credentials file, to place the access key and secret admission key you obtained when you lot created your DigitalOcean Space. The file will be located at ~/.aws/credentials on Mac and Linux, or C:\Users\USERNAME\.aws\credentials on Windows. If you have previously saved AWS credentials, you can read about keeping multiple sets of credentials for farther guidance.

Open your command prompt, make sure y'all're in your Users directory, have access to an administrative sudo user, and create the .aws directory with the credentials file within.

                      
  1. sudo mkdir .aws && touch .aws/credentials

Open the file, and paste the post-obit code inside, replacing your_access_key and your_secret_key with your respective keys.

credentials

          [default] aws_access_key_id=your_access_key            aws_secret_access_key=your_secret_key                  

Now your access to Spaces via the AWS SDK will exist authenticated, and we can move on to creating the application.

Install Node.js Dependencies

To brainstorm, create a directory in which you would similar to place your Node.js application and navigate to the directory. For this demonstration, we will create our project in spaces-node-app in the sites directory.

                      
  1. mkdir sites/spaces-node-app && cd sites/spaces-node-app

Create a new package.json file for your project. Paste the code below into the file.

package.json

                      {            "proper noun"            :            "spaces-node-app"            ,            "version"            :            "one.0.0"            ,            "main"            :            "server.js"            ,            "scripts"            :            {            "starting time"            :            "node server.js"            }            ,            "license"            :            "MIT"            }                  

This is a basic package.json file listing the proper name, version number, and license of our awarding. The scripts field volition allow us to run a Node.js server by typing npm commencement instead of node server.js.

We will install all of our dependencies with the npm install command, followed by the names of the four dependencies in our projection.

                      
  1. npm install aws-sdk express multer multer-s3

After running this command, the packet.json file should be updated. These dependencies will aid usa in connecting to the DigitalOcean Spaces API, creating a web server, and treatment file uploads.

  • aws-sdk — AWS SDK for JavaScript will allow us to access S3 through a JavaScript API.
  • express — Express is a web framework that will allow u.s. to quickly and efficiently set up a server.
  • multer — Multer is middleware that will handle file uploads.
  • multer-s3 — Multer S3 extends file uploads to S3 object storage, and in our case, DigitalOcean Spaces.

Now that nosotros accept our project location and dependencies prepare, we can set up the server and front-end views.

Annotation: npm install saves dependencies to the parcel.json file by default in current versions of Node. If you are running an older version of Node, you volition have to add together the --salvage flag to your npm install command to ensure that package.json gets updated.

Create the Front Terminate of the Application

First, let's create files for the public views of our application. This is what the user will run into on the front end. Create a public directory in your projection, with index.html, success.html, and fault.html. All three of these files will have the beneath HTML skeleton, with unlike contents in the body. Write the following code into each file.

                                    <!              DOCTYPE              html              >                                                      <html              lang                              =                "en"                            >                                                      <head              >                                                      <meta              charset                              =                "utf-8"                            >                                                      <meta              proper name                              =                "viewport"                            content                              =                "width=device-width, initial-scale=i.0"                            >                                                      <title              >            DigitalOcean Spaces Tutorial                              </title              >                                                      <link              rel                              =                "stylesheet"                            href                              =                "./way.css"                            >                                                      </head              >                                                      <torso              >                        <!-- contents will go hither -->                                          </body              >                                                      </html              >                              

Write an mistake message in the body of error.html.

error.html

          ...                                          <h1              >            Something went wrong!                              </h1              >                                                      <p              >            File was not uploaded successfully.                              </p              >                        ...                  

Write a success message in the body of success.html.

success.html

          ...                                          <h1              >            Success!                              </h1              >                                                      <p              >            File uploaded successfully.                              </p              >                        ...                  

In index.html, we will create an HTML form with multipart/form-information. It volition consist of a simple file upload input and a submit button.

index.html

          ...                                          <h1              >            DigitalOcean Spaces Tutorial                              </h1              >                                                      <p              >            Please select a file and submit the form to upload an asset to your DigitalOcean Space.                              </p              >                                                      <form              method                              =                "postal service"                            enctype                              =                "multipart/course-data"                            activeness                              =                "/upload"                            >                                                      <label              for                              =                "file"                            >            Upload a file                              </label              >                                                      <input              type                              =                "file"                            proper name                              =                "upload"                            >                                                      <input              type                              =                "submit"                            course                              =                "button"                            >                                                      </form              >                        ...                  

Finally, allow'south create style.css and add just enough CSS to brand the awarding piece of cake to read.

mode.css

                      html            {            font-family            :            sans-serif;            line-height            :            one.5;            color            :            #333;            }            body            {            margin            :            0 auto;            max-width            :            500px;            }            label, input            {            brandish            :            block;            margin            :            5px 0;            }                  

With these three files, nosotros accept an upload form which makes up the main page of our small application, and nosotros accept success and error pages for the user.

Fix an Express Server Environment

We've created all the files for the forepart end of our awarding, but nosotros currently don't have a server set upwards or whatsoever mode to view them. We will set up a Node server with the Express web framework.

In the root directory of the projection, create a server.js file. At the tiptop, load in our iv dependencies with require(). We will route our awarding through the app instance of express.

server.js

                      // Load dependencies            const            aws            =            crave            (            'aws-sdk'            )            ;            const            express            =            require            (            'express'            )            ;            const            multer            =            require            (            'multer'            )            ;            const            multerS3            =            require            (            'multer-s3'            )            ;            const            app            =            express            (            )            ;                  

Our forepart is located in the public directory, then set that configuration beneath the dependencies.

server.js

                      ...            // Views in public directory            app.            apply            (express.            static            (            'public'            )            )            ;                  

We will road index.html, success.html, and error.html relative to the root of the server.

server.js

                      ...            // Main, error and success views            app.            get            (            '/'            ,            role            (            request,              response            )            {            response.            sendFile            (__dirname            +            '/public/index.html'            )            ;            }            )            ;            app.            get            (            "/success"            ,            function            (            asking,              response            )            {            response.            sendFile            (__dirname            +            '/public/success.html'            )            ;            }            )            ;            app.            get            (            "/error"            ,            function            (            request,              response            )            {            response.            sendFile            (__dirname            +            '/public/error.html'            )            ;            }            )            ;                  

Finally, we will tell the server which port to heed on. In this instance, 3001 is used, but you can set it to whatever available port.

server.js

                      ...            app.            heed            (            3001            ,            part            (            )            {            console.            log            (            'Server listening on port 3001.'            )            ;            }            )            ;                  

Save server.js and showtime the server. You can do this by running node server.js, or with npm start, the shortcut we ready in package.json.

                      
  1. npm get-go
                      

Output

> node server.js Server listening on port 3001.

Navigate to http://localhost:3001, and you will see the upload form, since we set alphabetize.html to be the root of the server.

DigitalOcean Spaces Node.js Upload Form

You can likewise navigate to http://localhost:3001/success and http://localhost:3001/fault to ensure those pages are routing properly.

Upload a File to a Space with Multer

Now that we have our server surroundings upwards and running properly, the terminal step is to integrate the grade with Multer and Multer S3 to make a file upload to Spaces.

You can utilise new aws.S3() to connect to the Amazon S3 client. For use with DigitalOcean Spaces, we'll need to prepare a new endpoint to ensure it uploads to the correct location. At the time of writing, nyc3 is the merely region available for Spaces.

In server.js, whorl back up to the height and paste the following code below the abiding declarations.

server.js

                      ...            const            app            =            limited            (            )            ;            // Prepare S3 endpoint to DigitalOcean Spaces            const            spacesEndpoint            =            new            aws.Endpoint            (            'nyc3.digitaloceanspaces.com'            )            ;            const            s3            =            new            aws.S3            (            {            endpoint            :            spacesEndpoint            }            )            ;                  

Using the instance from the multer-s3 documentation, nosotros will create an upload function, setting the bucket holding to your unique Space name. Setting acl to public-read will ensure our file is accessible to the public; leaving this blank will default to private, making the files inaccessible from the web.

server.js

                      ...            // Change saucepan holding to your Infinite name            const            upload            =            multer            (            {            storage            :            multerS3            (            {            s3            :            s3,            bucket            :            'your-space-here'            ,            acl            :            'public-read'            ,            primal            :            office            (            asking,              file,              cb            )            {            console.            log            (file)            ;            cb            (            null            ,            file.originalname)            ;            }            }            )            }            )            .            assortment            (            'upload'            ,            1            )            ;                  

The upload function is complete, and our last pace is to connect the upload form with code to send the file through and route the user accordingly. Ringlet to the lesser of server.js, and paste this code right above the app.mind() method at the end of the file.

server.js

                      ...            app.            mail service            (            '/upload'            ,            part            (            request,              response,              next            )            {            upload            (request,            response,            function            (            error            )            {            if            (error)            {            console.            log            (error)            ;            render            response.            redirect            (            "/error"            )            ;            }            console.            log            (            'File uploaded successfully.'            )            ;            response.            redirect            (            "/success"            )            ;            }            )            ;            }            )            ;                  

When the user clicks submit, a POST asking goes through to /upload. Node is listening for this Post, and calls the upload() function. If an fault is plant, the provisional statement volition redirect the user to the /mistake page. If information technology went through successfully, the user will be redirected to the /success page, and the file will exist uploaded to your Infinite.

Hither is the entire code for server.js.

server.js

                      // Load dependencies            const            aws            =            require            (            'aws-sdk'            )            ;            const            express            =            require            (            'limited'            )            ;            const            multer            =            require            (            'multer'            )            ;            const            multerS3            =            crave            (            'multer-s3'            )            ;            const            app            =            express            (            )            ;            // Set up S3 endpoint to DigitalOcean Spaces            const            spacesEndpoint            =            new            aws.Endpoint            (            'nyc3.digitaloceanspaces.com'            )            ;            const            s3            =            new            aws.S3            (            {            endpoint            :            spacesEndpoint            }            )            ;            // Change bucket belongings to your Infinite name            const            upload            =            multer            (            {            storage            :            multerS3            (            {            s3            :            s3,            bucket            :            'your-space-here'            ,            acl            :            'public-read'            ,            key            :            role            (            request,              file,              cb            )            {            console.            log            (file)            ;            cb            (            null            ,            file.originalname)            ;            }            }            )            }            )            .            assortment            (            'upload'            ,            one            )            ;            // Views in public directory            app.            utilize            (express.            static            (            'public'            )            )            ;            // Master, error and success views            app.            go            (            '/'            ,            function            (            asking,              response            )            {            response.            sendFile            (__dirname            +            '/public/alphabetize.html'            )            ;            }            )            ;            app.            get            (            "/success"            ,            role            (            request,              response            )            {            response.            sendFile            (__dirname            +            '/public/success.html'            )            ;            }            )            ;            app.            get            (            "/error"            ,            office            (            request,              response            )            {            response.            sendFile            (__dirname            +            '/public/error.html'            )            ;            }            )            ;            app.            post            (            '/upload'            ,            function            (            request,              response,              adjacent            )            {            upload            (request,            response,            function            (            error            )            {            if            (error)            {            console.            log            (fault)            ;            return            response.            redirect            (            "/error"            )            ;            }            console.            log            (            'File uploaded successfully.'            )            ;            response.            redirect            (            "/success"            )            ;            }            )            ;            }            )            ;            app.            listen            (            3001            ,            office            (            )            {            console.            log            (            'Server listening on port 3001.'            )            ;            }            )            ;                  

Stop the Node server by typing Command + C in the command prompt, and restart it to ensure the new changes are applied.

                      
  1. npm start

Navigate to the root of the project, select a file, and submit the course. If everything was set properly, you will be redirected to the success page, and a public file will exist available on your DigitalOcean Space.

Success confirmation page following upload

Assuming the file you uploaded was test.txt, the URL of the file will be https://your-space-here.nyc3.digitaloceanspaces.com/test.txt.

Mutual reasons for an unsuccessful transaction would be incorrect credentials, credentials file in the wrong location, or an incorrect bucket proper name.

Determination

Congratulations, you've set upward a Node.js and Limited application to upload static avails to object storage!

You lot can play around with the code of this DigitalOcean Spaces Node App by remixing the project hither.

Additional precautions such as authentication must be taken to put this blazon of application into product, but this is a skilful starting point to make your spider web app functional with DigitalOcean Spaces. For more information virtually object storage, read An Introduction to DigitalOcean Spaces.

lunatheable.blogspot.com

Source: https://www.digitalocean.com/community/tutorials/how-to-upload-a-file-to-object-storage-with-node-js

0 Response to "Upload File to Vultr From Google Drive"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel