Uploading a file to Oracle Object Storage using Node.JS
Published: 2023-07-23 21:01:21

We extend the tutorial of [How to upload a file in a full-stack React app](https://dev.to/farisdurrani/how-to-upload-a-file-in-a-full-stack-react-app-4ohn) to learn how to upload a file to Oracle Cloud's Object Storage using OCI's NPM SDK.

## Install the SDK
First, we install the SDK in the backend:
```sh
npm i oci-common oci-sdk
```

Make sure you also have your OCI profile configured with your API key as shown [here](https://dev.to/farisdurrani/setting-up-the-oci-configuration-file-using-api-keys-96c).

## Edit the `index.ts` file in backend

We now edit the `backend/index.ts` file to the following to receive the file from the HTTP request call, download it to a local storage, and then upload it to Object Storage:
```ts
import express, { Request } from "express";
import cors from "cors";
import multer from "multer";
import fs from "fs";
import os = require("oci-objectstorage");
import { ConfigFileAuthenticationDetailsProvider } from "oci-common";

// Create express app
const app = express();

app.use(express.json());
app.use(cors());

app.get("/helloText", (req, res) => {
  res.send({ myResponse: "Hello World!" });
});

const provider = new ConfigFileAuthenticationDetailsProvider(
  "~/.oci/config",
  "DEFAULT"
);

const OCI_BUCKET_NAMESPACE = "id9ek7fershl";

const client = new os.ObjectStorageClient({
  authenticationDetailsProvider: provider,
});

const upload = multer({ dest: "tmp/uploads/" });
app.post("/putObject", upload.single("file"), async (req, res) => {
  console.log(`${req.method} ${req.path}`);
  const { bucketName, objectName } = req.body;
  try {
    if (!req.file) {
      throw new Error("No file uploaded");
    }
    const { path: filePath, originalname: fileName } = req.file;
    const result = await putObject({
      bucketName,
      filePath,
      objectName,
    });
    console.log(`200 ${req.path}`);
    res.status(200).send(result);
  } catch (err) {
    console.error(err);
    res.status(500).send(err);
  }
});

/**
 * Put an object (replaces if exists) into an OCI bucket
 * @param putObjectDetails
 * @returns the response from the putObject call
 */
export async function putObject(putObjectDetails: {
  bucketName: string;
  filePath: string;
  objectName: string;
}) {
  const { bucketName, filePath, objectName } = putObjectDetails;
  console.log(
    `Beginning putting object ${objectName} into bucket ${bucketName}`
  );

  const content = convertFileToUint8Array(filePath);
  const putObjectRequest: os.requests.PutObjectRequest = {
    namespaceName: OCI_BUCKET_NAMESPACE,
    bucketName: bucketName,
    putObjectBody: content,
    objectName: objectName,
    contentLength: content.length,
  };
  const putObjectResponse = await client.putObject(putObjectRequest);
  console.log(
    `Successfully put object ${objectName} into bucket ${bucketName}`
  );
  return putObjectResponse;
}

function convertFileToUint8Array(filePath: string): Uint8Array {
  const data = new Uint8Array(fs.readFileSync(filePath));
  return data;
}

app.listen(8000, () => {
  console.log(`Server is running on port ${8000}`);
});
```

Of course, remember to change the namespace and config profile details to your own. Happy coding!


***Safe harbor statement***
The information provided on this channel/article/story is solely intended for informational purposes and cannot be used as a part of any contractual agreement. The content does not guarantee the delivery of any material, code, or functionality, and should not be the sole basis for making purchasing decisions. The postings on this site are my own and do not necessarily reflect the views or work of Oracle or Mythics, LLC.

*This work is licensed under a* [*Creative Commons Attribution 4.0 International License*](http://creativecommons.org/licenses/by/4.0/)*.*