How to Use Node.js to Upload Files to Alibaba Cloud Object Storage

Requirements

For you to follow through with this tutorial you will require the following:

  1. Subscribe to the Alibaba Cloud Object Storage Service to get secret access keys.
  2. Run Node.js and npm on your machine. Node.js Downloads contains further information on how to go about Node installation.

How to Add Access Keys to the Credentials File

To begin with, the Alibaba Cloud OSS supports RESTful API operations and SDKs for most languages. In this tutorial, we are going to use the open-source OSS JavaScript SDK for node.js. We need to first install the ali-oss like so:

npm install ali-oss
npm install co

Initializing the Client

This method is applied in the synchronous mode. It involves creating an object app.js like so

var co = require('co');
var OSS = require('ali-oss');
var client = new OSS({
region: '<Your region>',
accessKeyId: '<Your AccessKeyId>',
accessKeySecret: '<Your AccessKeySecret>'
});
  1. secure: to be used in conjunction with region. Access using HTTP if secure is specified to true.
  2. endpoint: when you specify an endpoint, it is alright to ignore the region. Specifying HTTPS for endpoint is allowed.
  3. bucket: It is required that you call the useBucket interface first if the bucket is not specified.
  4. time-out: by default, the value is 60 secs. It is a parameter to specify the OSS API time-out.

Installing Dependencies

In this step we shall install node.js dependencies so that we can have a directory where our node application will be located. For purposes of this tutorial, we create our app in OSS-node-app like so:

mkdir sites/OSS-node-app && cd sites/OSS-node-app
{
"name": "OSS-node-app",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"license": "MIT"
}
npm install ali-oss express
  1. ali-OSS — Alibaba SDK for JavaScript to enable us access JavaScript API.
  2. express — Express enables quick and efficient set up of our server.

Creating the Front-end App

We shall begin by creating files for the public views of our application, which is what will be visible by users. We are going to create a public folder using index.html, success.html, and error.html. Our three files shall have the HTML skeleton indicated in the below, only with different content. In all the files, paste the code below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OSS Node Tutorial</title> <link rel="stylesheet" href="./style.css">
</head>
<body> <!—your content here --></body></html>
<h1>Something went wrong!</h1>
<p>Uploading the file was unsuccessful.</p>
<h1>Success!</h1>
<p>File uploaded successfully.</p>
<h1>OSS Tutorial</h1><p>Please select a file and submit form to upload.</p><form method="post" enctype="multipart/form-data" action="/upload">
<label for="file">Upload a file</label>
<input type="file" name="upload">
<input type="submit" class="button">
</form>
html {
font-family: sans-serif;
line-height: 1.5;
color: #333;
}
body {
margin: 0 auto;
max-width: 500px;
}
label,
input {
display: block;
margin: 5px 0;
}

Setting Up Server with Express

We are going to wet up a node.js server using the Express framework. To begin with, create a server.js file in the project’s root directory. We then need to use require() to load the four dependencies and then route the app through Express’s app instance like so:

server.js
// Load dependencies
const ali = require(ali-oss');
const express = require('express');
const app = express();
// Views in public directory
app.use(express.static('public'));
// Main, error and success views
app.get('/', function (request, response) {
response.sendFile(__dirname + '/public/index.html');
});
app.get("/success", function (request, response) {
response.sendFile(__dirname + '/public/success.html');
});
app.get("/error", function (request, response) {
response.sendFile(__dirname + '/public/error.html');
});
server.js
app.listen(5000, function () {
console.log('Server listening on port 5000.');
});
npm start
Output
> node server.js
Server listening on port 5000.

Uploading our Files

Our server is all set up, so we shall then integrate our form to ali-oss to enable us upload our first file to the Alibaba OSS.

server.js
const app = express();
// Set endpoint to Alibaba OSS
const spacesEndpoint = new OSS.Endpoint(' http://oss-cn-hangzhou.aliyuncs.com.');
const s3 = new OSS({
endpoint: spacesEndpoint
});
var co = require('co');
var OSS = require('ali-oss')
var client = new OSS({
region: '<Your region>',
accessKeyId: '<Your AccessKeyId>',
accessKeySecret: '<Your AccessKeySecret>',
bucket: 'Your bucket name'
});
co(function* () {
var result = yield client.put('object-key', 'local-file');
console.log(result);
}).catch(function (err) {
console.log(err);
});
var co = require('co');
var OSS = require('ali-oss');
var fs = require('fs');
var client = new OSS({
region: '<Your region>',
accessKeyId: '<Your AccessKeyId>',
accessKeySecret: '<Your AccessKeySecret>',
bucket: 'Your bucket name'
});
co(function* () {
// use 'chunked encoding'
var stream = fs.createReadStream('local-file');
var result = yield client.putStream('object-key', stream);
console.log(result);
// do not use 'chunked encoding'
var stream = fs.createReadStream('local-file');
var size = fs.statSync('local-file').size;
var result = yield client.putStream(
'object-key', stream, {contentLength: size});
console.log(result);
}).catch(function (err) {
console.log(err);
});
var co = require('co');
var OSS = require('ali-oss');
var client = new OSS({
region: '<Your region>',
accessKeyId: '<Your AccessKeyId>',
accessKeySecret: '<Your AccessKeySecret>',
bucket: 'Your bucket name'
});
co(function* () {
var result = yield client.put('object-key', new Buffer('hello world'));
console.log(result);
}).catch(function (err) {
console.log(err);
});
  1. name {String}: Object name
  2. file {String|File}: File path or HTML5 Web File
  3. [options] {Object}: Optional parameter
  4. [checkpoint] {Object}: Endpoint checkpoint used in resumable upload. If this parameter is set, the upload starts from the endpoint. If it is not set, the upload restarts.
  5. [partSize] {Number}: Part size
  6. [progress] {Funtion}: A generator function. It contains three parameters:
  7. (percentage {Number}: upload progress (a decimal range from 0 to 1)
  8. (checkpoint {Object}: Endpoint checkpoint
  9. (res {Object}): Response returned after a single part is successfully uploaded
  10. [meta] {Object}: Header meta inforamtion defined by users with a prefix x-oss-meta-
  11. [headers] {Object}: Extra headers. See RFC 2616 for more information.
  12. ‘Cache-Control’: General header used to implement cache mechanisms by specifying a command in HTTP requests and responses. For example: Cache-Control: public, no-cache
  13. ‘Content-Disposition’: Used to indicate the disposition form of a response, which can be an internal reference (a part of a webpage or a page) or an attachment downloaded and saved locally. For example: Content-Disposition: somename
  14. ‘Content-Encoding’: Used to compress data of specific media type. For example: Content-Encoding: gzip
  15. ‘Expires’: Expiration time. For example: Expires: 3600000
var co = require('co');
var OSS = require('ali-oss')
var client = new OSS({
region: '<Your region>',
accessKeyId: '<Your AccessKeyId>',
accessKeySecret: '<Your AccessKeySecret>',
bucket: 'Your bucket name'
});
co(function* () {
var result = yield client.multipartUpload('object-key', 'local-file', {
progress: function* (p) {
console.log('Progress: ' + p);
}
meta: {
year: 2017,
people: 'test'
}
});
console.log(result);
var head = yield client.head('object-key');
console.log(head);
}).catch(function (err) {
console.log(err);
});
var progress = function (p) {
return function (done) {
console.log(p);
done();
};
};

Conclusion

Congratulations, you have made it to the end. We have successfully set up an Express application to upload objects to our Alibaba Cloud Object Storage Service (OSS) space! Don’t have an Alibaba Cloud account? Sign up for an account and try over 40 products for free worth up to $1200. Get Started with Alibaba Cloud to learn more.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com